我正在尝试调用服务器中托管的rest Web api。 java.net.ConnectException:无法连接到/10。..***:45。 这是POST方法,将JSON作为参数传递。
CommonAsyncTask cat=new CommonAsyncTask(MainActivity.this,jsonParam,1);
cat.delegate = MainActivity.this;
cat.execute(getResources().getString(R.string.url));
我能够打开连接,但是当我尝试在HttpURLConnection对象上获取getOutputstream时发生错误。
这是从Android调用用asp.net编写的Web API的正确方法吗? 如果是,请帮助我解决此错误。
public class CommonAsyncTask extends AsyncTask<String, Integer, String> {
JSONObject params;
// private ProgressDialog progressDialog = null;
Context mContext;
public AsyncResponse delegate = null;
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private int taskType;
private ProgressDialog progressDialog = null;
InputStream is;
public CommonAsyncTask(Context mContext, JSONObject params, int taskType) {
this.mContext = mContext;
this.params = params;
this.taskType = taskType;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
/*progressDialog = ProgressDialog.show(mContext, "Please wait",
"Connecting");
progressDialog.setCancelable(true);*/
}
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String result = "";
try {
/*
* Communication with Webservice
*/
switch (taskType) {
case POST_TASK:
Log.d("TAG:","POSTT");
URL url = new URL(urls[0]);
Log.d("b4 con","here");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
Log.d("after con.open","here");
conn.setRequestMethod("POST");
Log.d("seting post","here");
conn.setDoOutput(true);
Log.d("DOOUTPUT-true","here");
conn.setDoInput(true);
Log.d("DOinputPUT-true","here");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
Log.d("contenttype-json","here");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
Log.d("data outputstream","here");
wr.writeBytes(params.toString());
wr.flush();
wr.close();
Log.d("b4","conn.connect");
conn.connect();
int responsePostCode = conn.getResponseCode();
if(responsePostCode>=400){
is = conn.getErrorStream();
}
else{
is=conn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(
is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
result = response.toString();
Log.d("LWCP", "Response: " + result);
break;
case GET_TASK:
/*
* String query = String.format("mobile=%s",
* URLEncoder.encode(cid, "utf-8"));
*/
URL obj = new URL(urls[0]);
// URL obj = new URL(url[0] + "?mobile=" + cid);
HttpURLConnection con = (HttpURLConnection) obj
.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.d("Sending'GET'request to:", urls + "");
Log.d("Response Code : ", responseCode + "");
Log.d("url-",urls[0]);
if(responseCode>=400){
is = con.getErrorStream();
}
else{
is=con.getInputStream();
}
BufferedReader inReader = new BufferedReader(
new InputStreamReader(is));
String inLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inLine = inReader.readLine()) != null) {
responseBuffer.append(inLine);
}
inReader.close();
con.connect();
result = responseBuffer.toString();
Log.d("LWCP", "Response: " + result);
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
//progressDialog.dismiss();
delegate.processFinish(result);
}
}
共享我的日志
D/TAG:: POSTT
D/b4 con: here
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/after con.open: here
D/seting post: here
D/DOOUTPUT-true: here
D/DOinputPUT-true: here
D/contenttype-json: here
W/System.err: java.net.ConnectException: Failed to connect to /10.142.173.112:45
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.example.restcall.CommonAsyncTask.doInBackground(CommonAsyncTask.java:78)
at com.example.restcall.CommonAsyncTask.doInBackground(CommonAsyncTask.java:19)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)