- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将数据发送到在本地主机上运行的 jsp 文件。当我在手机上单击“提交”时,应用程序失败,并显示不幸的是,应用程序已停止。
登录任务:
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private LoginActivity activity;
private int id = -1;
public LoginTask(LoginActivity activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
@Override
protected void onPreExecute()
{
progressDialog.show();
}
@Override
protected Integer doInBackground(String... arg0)
{
String result = "";
int responseCode = 0;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.100:8080/test/AndroidCheck.jsp");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", arg0[0]));
nameValuePairs.add(new BasicNameValuePair("password", arg0[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
int executeCount = 0;
HttpResponse response;
do
{
progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
executeCount++;
response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
} while (executeCount < 5 && responseCode == 408);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null)
{
result = line.trim();
}
id = Integer.parseInt(result);
}
catch (Exception e) {
responseCode = 408;
e.printStackTrace();
}
return responseCode;
}
@Override
protected void onPostExecute(Integer headerCode)
{
progressDialog.dismiss();
if(headerCode == 202)
activity.login(id);
else
activity.showLoginError("");
}
}
登录 Activity :
public class LoginActivity extends Activity {
protected static final int LOGIN_REQUEST_CODE = 0;
protected static final int RECOVER_REQUEST_CODE = 1;
protected static final int REGISTER_REQUEST_CODE = 2;
public static final int LOGOUT_RESULT_CODE = 2;
SharedPreferences sharedPreferences;
private EditText username;
private EditText password;
private Button btnLogin;;
private final Class<?> LOGIN_DESTINATION = AndroidNavigationTabsActivity.class;
@Override
protected void onCreate(Bundle savedInstanceState)
{
sharedPreferences = getPreferences(MODE_PRIVATE);
super.onCreate(savedInstanceState);
if( sharedPreferences.getBoolean("user_logged_in", false))
{
startActivityForResult(
new Intent(LoginActivity.this, LOGIN_DESTINATION),
LOGIN_REQUEST_CODE);
}
setContentView(R.layout.login_activity);
username=(EditText)this.findViewById(R.id.username);
password=(EditText)this.findViewById(R.id.password);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(loginOnClickListener);
}
protected OnClickListener loginOnClickListener = new OnClickListener()
{
public void onClick(View v)
{
ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Logging in...");
progressDialog.setCancelable(false);
LoginTask loginTask = new LoginTask(LoginActivity.this, progressDialog);
loginTask.execute(username.getText().toString(),password.getText().toString());
}
};
public void showLoginError(String result)
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage(R.string.login_invalid_error);
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
public void login(int id)
{
sharedPreferences.edit().putBoolean("user_logged_in", true).commit();
startActivityForResult(
new Intent(LoginActivity.this, LOGIN_DESTINATION),
LOGIN_REQUEST_CODE);
}
}
当我在手机上点击提交时,它显示错误( toast )。 jsp 页面 (AndroidCheck.jsp) 向我显示 null
(我试图在网页上显示,我在手机中输入的内容:用户名和登录名)。我不知道,问题出在哪里......
最佳答案
这里的问题几次改变了方向(从 GET 到 POST)。为了创建一个可能对您有帮助的简单但广泛的答案,我在下面提供了一个示例,它可以在 Android 上通过 HttpClient
执行 POST 和 GET(每个都使用 AsyncTask
)。
请记住,此示例并不是在 Android 上执行 HTTP 的唯一方法,并且在一些地方过于简单。它旨在帮助您开始使用 HttpClient
。
还有其他 HTTP 客户端,包括在某些情况下仅使用 java.net
,有关详细信息,请参阅此博客文章:http://android-developers.blogspot.com/2011/09/androids-http-clients.html .
此外,您可能需要考虑使用许多优秀的第三方库之一,它们可以使事情变得更容易,例如 loopj 的异步 Android Http 客户端:http://loopj.com/android-async-http/ .
请注意,我使用了 http://httpbin.org/在示例中作为服务器端点。 httpbin.org 是一个很棒的测试服务器,让您可以发送和检查各种 HTTP 数据。
Activity
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
public class MainActivity extends Activity {
private ProgressDialog dialog;
private Button get;
private Button post;
private TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output = (TextView) findViewById(R.id.output);
get = (Button) findViewById(R.id.get_button);
post = (Button) findViewById(R.id.post_button);
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
output.setText("");
new SimpleHttpGetTask(MainActivity.this).execute("http://httpbin.org/get");
}
});
post.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
output.setText("");
new SimpleHttpPostTask(MainActivity.this).execute("http://httpbin.org/post", "param1name", "param1Value");
}
});
}
@Override
protected void onPause() {
super.onPause();
if (dialog != null) {
dialog.dismiss();
}
}
private class SimpleHttpGetTask extends AsyncTask<String, Void, String> {
private final Context context;
public SimpleHttpGetTask(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
dialog.setMessage("doing a GET...");
dialog.show();
}
@Override
protected String doInBackground(String... args) {
if (args == null || args.length != 1) {
Log.w("TAG", "args size must be 1: URL to invoke");
return null;
}
String url = args[0];
Log.d("TAG", "hitting URL:" + url);
// AndroidHttpClient has more reasonable default settings than "DefaultHttpClient", but it was only added in API 8
// (if you need to support API levels lower than 8, I'd create your own HttpClient with similar settings [see bottom of page for example])
AndroidHttpClient client = AndroidHttpClient.newInstance("Android-MyUserAgent");
HttpRequestBase request = new HttpGet(url);
HttpResponse response = null;
try {
response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
// use the response here
// if the code is 200 thru 399 it worked or was redirected
// if the code is >= 400 there was a problem
Log.d("TAG", "http GET completed, code:" + code + " message:" + message);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
// convert stream if gzip header present in response
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// returning the string here, but if you want return the code, whatever
String result = convertStreamToString(instream);
Log.d("TAG", "http GET result (as String):" + result);
return result;
} finally {
if (instream != null) {
instream.close();
}
}
}
} catch (Exception e) {
Log.e("TAG", "Error with HTTP GET", e);
} finally {
client.close();
}
return null;
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (result != null) {
// use response back on UI thread here
output.setText(result);
}
}
}
private class SimpleHttpPostTask extends AsyncTask<String, Void, String> {
private final Context context;
public SimpleHttpPostTask(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
dialog.setMessage("doing a POST...");
dialog.show();
}
@Override
protected String doInBackground(String... args) {
if (args == null || args.length != 3) {
// in real use you might want to make a better request class of your own to pass in, instead of using a bunch of strings
Log.w("TAG", "args size must be 3: URL to invoke, and 1st param (name/value) to submit");
return null;
}
String url = args[0];
String param1Name = args[1];
String param1Value = args[2];
Log.d("TAG", "hitting URL:" + url);
// AndroidHttpClient has more reasonable default settings than "DefaultHttpClient", but it was only added in API 8
// (if you need to support API levels lower than 8, I'd create your own HttpClient with similar settings [see bottom of page for example])
AndroidHttpClient client = AndroidHttpClient.newInstance("Android-MyUserAgent");
HttpRequestBase request = new HttpPost(url);
HttpResponse response = null;
try {
// there are different kinds of POSTS, url encoded form is ONE
// (which you need depends on what you're trying to post and how the server is implemented)
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(param1Name, param1Value));
((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
// use the response here
// if the code is 200 thru 399 it worked or was redirected
// if the code is >= 400 there was a problem
Log.d("TAG", "http POST completed, code:" + code + " message:" + message);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
// convert stream if gzip header present in response
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// returning the string here, but if you want return the code, whatever
String result = convertStreamToString(instream);
Log.d("TAG", "http GET result (as String):" + result);
return result;
} finally {
if (instream != null) {
instream.close();
}
}
}
} catch (Exception e) {
Log.e("TAG", "Error with HTTP POST", e);
} finally {
client.close();
}
return null;
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (result != null) {
// use response back on UI thread here
output.setText(result);
}
}
}
// this is OVERSIMPLE (for the example), in the real world, if you have big responses, use the stream
private static String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is, "UTF-8").useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
/*
// ONE example of some default settings for DefaultHttpClient (if you can't use AndroidHttpClient, or want more fine grained control)
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
HttpConnectionParams.setSoTimeout(params, 20000);
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpClientParams.setRedirecting(params, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(params);
*/
}
布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HTTP BASICS" />
<Button
android:id="@+id/get_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HTTP GET" />
<Button
android:id="@+id/post_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HTTP POST" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
list
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.totsp.httptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.com.totsp.httptest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
关于android - 从android发送数据到jsp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15310638/
我正在使用 voip 推送通知制作 ios 应用程序。 我想从 Node js 发送 voip 推送通知,但不是很好。 我阅读了本教程 CallKit iOS Swift Tutorial for V
我编写了一个服务器,当浏览器尝试连接到某些站点时,它会检查黑名单并发回 404,但是当我调用 send() 时没有错误,但消息不会出现在网络上浏览器,除非我关闭连接? 有什么建议吗? 接受来自浏览器的
#include int main() { char c = getchar(); //EOF (ctrl + d ) while( ( c = getchar() ) != '?'
我正在尝试使用MailMessage对象通过PowerShell发送电子邮件。该脚本使用Import-CSV来使用文件,然后在电子邮件正文中使用ConvertTo-HTML。由于我要发送的电子邮件客户
我需要创建一个脚本,每 30 秒对网络流量进行一次采样并存储发送/接收的字节。该数据随后用于绘制图形。我编写了一个在 Windows 2012 上完美运行的程序,但我意识到某些 cmdlet 在以前的
我正在运行“autoit3.chm”文件。当它运行时,我想发送一个向下键箭头,但它不起作用: $file = FileGetShortName("C:\Users\PHSD100-SIC\Deskto
当我使用网络浏览器测试我的程序时,我可以很好地写入套接字/FD,所以我决定循环它并在连接中途切断连接,我发现了一个问题。 send() 能够在套接字不可用时关闭整个程序。我认为问题在于该程序陷入了第
我正在运行“autoit3.chm”文件。当它运行时,我想发送一个向下键箭头,但它不起作用: $file = FileGetShortName("C:\Users\PHSD100-SIC\Deskto
所以我试图向自己发送数据并接收数据然后打印它,现在我已经测试了一段时间,我注意到它没有发送任何东西,事实上,也许它是,但我没有正确接收它,我需要这方面的帮助。 这就是我用来发送数据的
问题:开发人员创建自己的序列化格式有多常见?具体来说,我使用 java 本质上将对象作为一个巨大的字符串发送,并用标记来分隔变量。 我的逻辑:我选择这个是因为它几乎消除了语言依赖性(忽略java的修改
我必须在 Linux 上编写一个应用程序,该应用程序需要与具有自定义以太网类型的设备进行通信。甚至在如何编写这样的应用程序中也有很多解决方案。一个缺点是需要 root 访问权限(AFAIK)。之后释放
我有一个包含三个单选按钮选项的表单。我需要将表单数据提交到另一个文件,但由于某种原因,发送的数据包含所选单选按钮的值“on”,而不是 value 属性的值。 我尝试通过 post() 函数手动操作和发
基本上我想实现这样的目标: Process 1 Thread 1 Receive X from process 2 Thread 2 Receive Y from proces
我目前正在 Google App Engine 上开发一个系统,对它还很陌生,我正在使用 Java 平台进行开发。我在 servlet 之间发送 session 对象时遇到问题。我已经在 appeng
当我尝试将“this”(触发的元素)作为参数发送给函数时,函数收到“Object[Document build.php]”作为参数,而不是触发的元素。请让我知道我的错误: function set(a
我正在寻找让我的应用响应联系人 > 发送的魔法咒语。我希望能够接收联系人的 URI 以便检索联系人。谁有 list 过滤器/代码 fragment 吗? 最佳答案 我没有睾丸,但您可以尝试基于 ACT
关于我心爱的套接字的另一个问题。我先解释一下我的情况。之后我会告诉你是什么困扰着我。 我有一个客户端和一个服务器。这两个应用程序都是用 C++ 编写的,实现了 winsock2。连接通过 TCP 和
我看到了这篇文章 http://www.eskimo.com/~scs/cclass/int/sx5.html 但这部分让我感到困惑:如果我们已经使用 send_array 或 send_array_
我对这行代码有疑问。我必须将一个数据包带到一个端口并重新发送到接口(interface)(例如:eth0)。我的程序成功地从端口获取数据包,但是当我重新发送(使用 send())到接口(interfa
我正在尝试编写一个 X11 输入驱动程序,它可以使用我的 Android 手机上的触摸屏来移动和单击鼠标。我可以正常移动鼠标,但我无法让应用程序正确识别点击。我当前的代码位于 https://gist
我是一名优秀的程序员,十分优秀!