Java Android 将发布数据发送到网络服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19446027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android sending post data to webservice
提问by Millerbean
Hi I'm trying to send data to a webservice
嗨,我正在尝试将数据发送到网络服务
String url = "https://www.myurl.com";
String url = " https://www.myurl.com";
URL urlobj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) urlobj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters = GenerateUrlParameters(data);
con.setDoOutput(true);
con.setDoInput(true);
Log.i("test", "hit1");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
Log.i("test", "hit2");
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Hit1 is hit but it fails in the next line and doesn't hit hit2. What am I doing wrong ?
Hit1 被击中但它在下一行失败并且没有击中 hit2。我究竟做错了什么 ?
My logcat
我的日志
10-18 09:17:33.302: D/gralloc_goldfish(2228): Emulator without GPU emulation detected.
10-18 09:17:33.322: W/TextLayoutCache(2228): computeValuesWithHarfbuzz -- need to force to single run
10-18 09:17:37.862: I/test(2228): hit1
10-18 09:17:37.872: D/AndroidRuntime(2228): Shutting down VM
10-18 09:17:37.872: W/dalvikvm(2228): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
10-18 09:17:37.912: E/AndroidRuntime(2228): FATAL EXCEPTION: main
10-18 09:17:37.912: E/AndroidRuntime(2228): java.lang.IllegalStateException: Could not execute method of the activity
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.view.View.onClick(View.java:3039)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.view.View.performClick(View.java:3480)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.view.View$PerformClick.run(View.java:13983)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.os.Handler.handleCallback(Handler.java:605)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.os.Looper.loop(Looper.java:137)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.app.ActivityThread.main(ActivityThread.java:4340)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.lang.reflect.Method.invoke(Method.java:511)
10-18 09:17:37.912: E/AndroidRuntime(2228): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-18 09:17:37.912: E/AndroidRuntime(2228): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-18 09:17:37.912: E/AndroidRuntime(2228): at dalvik.system.NativeStart.main(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228): Caused by: java.lang.reflect.InvocationTargetException
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.lang.reflect.Method.invoke(Method.java:511)
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.view.View.onClick(View.java:3034)
10-18 09:17:37.912: E/AndroidRuntime(2228): ... 11 more
10-18 09:17:37.912: E/AndroidRuntime(2228): Caused by: android.os.NetworkOnMainThreadException
10-18 09:17:37.912: E/AndroidRuntime(2228): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-18 09:17:37.912: E/AndroidRuntime(2228): at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
10-18 09:17:37.912: E/AndroidRuntime(2228): at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:280)
10-18 09:17:37.912: E/AndroidRuntime(2228): at dk.example.epaypayment.EpayHttpRequest.MakePayment(EpayHttpRequest.java:53)
10-18 09:17:37.912: E/AndroidRuntime(2228): at dk.example.epaypayment.MainActivity.sendMessage(MainActivity.java:37)
10-18 09:17:37.912: E/AndroidRuntime(2228): ... 14 more
10-18 09:22:38.232: I/Process(2228): Sending signal. PID: 2228 SIG: 9
采纳答案by AKSH
Call sendPostRequest(String username, String pass)
method with parameters. You can call this method from the UI thread, the request will be sent from a different thread (AsyncTask
is embedded).
sendPostRequest(String username, String pass)
带参数的调用方法。您可以从 UI 线程调用此方法,请求将从不同的线程(AsyncTask
嵌入)发送。
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername "
+ paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx");// replace with your url
httpPost.addHeader("Content-type",
"application/x-www-form-urlencoded");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
"UserId", paramUsername); // Make your own key value pair
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
"Password", paramPassword);// make your own key value pair
// You can add more parameters like above
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePair);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient
.execute(httpPost);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("First Exception coz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second Exception coz of HttpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out
.println("An Exception given because of UrlEncodedFormEntity argument :"
+ uee);
uee.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
回答by someGuy
Well, I could suggest to do it in little higher abstraction, using HttpClient.
好吧,我可以建议使用 HttpClient 以更高的抽象来完成它。
DefaultHttpClient httpClient = null;
HttpParams my_httpParams = new BasicHttpParams();
httpClient = new DefaultHttpClient(my_httpParams);
and then sending
然后发送
HttpPost httpPost = new HttpPost(stringUri);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("charset", "utf-8");
if (!TextUtils.isEmpty(someStringToSend)) {
httpPost.setEntity(new StringEntity(someStringToSend, HTTP.UTF_8));
}
HttpResponse responsePOST = httpClient.execute(httpPost);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
response = EntityUtils.toString(resEntity, HTTP.UTF_8);
}
I have not tested it but should work.
我还没有测试过,但应该可以工作。
回答by user2699728
Try implementing this code ,it should work. And if your Android version is above 4.0, then you will have to compulsory use Asyn Task , So that this http request do not run on Main Thread. otherwise app will crash. If the app is using HTTPGET or HTTPPOST method and is running on Main Thread ,it will crash. Asyn TAsk is the Solution.
尝试实现此代码,它应该可以工作。而如果你的安卓版本在4.0以上,那你就必须强制使用Asyn Task,这样这个http请求就不会在主线程上运行了。否则应用程序会崩溃。如果应用程序使用 HTTPGET 或 HTTPPOST 方法并在主线程上运行,它将崩溃。异步任务是解决方案。
HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json=new JSONObject();
HttpPost post = new HttpPost(url1);
try {
json.put("Key","your value");
json.put("Key", "Value");
StringEntity stringEntity = new StringEntity(json.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
response = client.execute(post);
Log.e("RESPONSE", response.toString());
String responseBody = EntityUtils
.toString(response.getEntity());
res= responseBody.toString();
Log.e("RESPONSE BODY", responseBody);