Build_HttpBody() 问题//httpPost.setEntity() - Android [英] Problems with a Build_HttpBody() // httpPost.setEntity() - Android
问题描述
我使用 AndroidStudio 开发 AndroidApps 我开始做一个简单的 HttpPost 请求,但我遇到了问题,我能找到的所有帖子都是这样做的:
private void CheckLoguin_Request(String User, String Pass){//声明变量HttpClient httpClient = new DefaultHttpClient();HttpPost 请求 = 新的 HttpPost(url_Loguin);HttpResponse 响应;列表BodyRequest_Elements = new ArrayList();BodyRequest_Elements.add(new BasicNameValuePair("user_name", User));BodyRequest_Elements.add(new BasicNameValuePair("user_passwd", Pass));Request.setEntity(new UrlEncodedFormEntity(BodyRequest_Elements));响应 = httpClient.execute(Request);//将响应写入日志Log.d("Http 响应:", Response.toString());}
但是当我尝试调试 App Android Studio 时,在这行中出现 2 个错误:
new UrlEncodedFormEntity(BodyRequest_Elements)//Error:(40, 27) error: unreported exception UnsupportedEncodingException;必须被捕获或声明被抛出响应 = httpClient.execute(Request);//Error:(41, 38) 错误:未报告的异常IOException;必须被捕获或声明被抛出
我可能需要安装更多的库或支持库吗?我做什么不好?任何人都可以帮助我吗?预先感谢并为我的英语感到抱歉!
PD1:如果您需要更多信息或代码,请告诉我!
2016 年更新
使用 HttpURLConnection 类,我们需要打开 BufferedWritter 以插入我们的实体值,如下代码:
//声明变量私有列表值列表;...public Check_Loguin_Request(Context cx,String url, List ListOfValues){this.cx = cx;this.Url = url;this.ListOfValues=ListOfValues;}@覆盖受保护的字符串 doInBackground(字符串...字符串){//声明变量输入流是 = null;字符串结果 = "";URL url = 新的 URL(url);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000);conn.setConnectTimeout(15000);conn.setRequestMethod("POST");conn.setDoInput(true);conn.setDoOutput(true);OutputStream os = conn.getOutputStream();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));writer.write(Build_HttpBody(ListOfValues));writer.flush();writer.close();os.close();//开始请求conn.connect();int ResponseCode = conn.getResponseCode();如果(响应代码 == 200){is = conn.getInputStream();String EntityResult = ReadResponse_HttpURLConnection(is);}别的 {throw new RuntimeException("状态码无效");}}
<小时><块引用>
注意 DefaultHttpClient 类已弃用 (2011)
有关此链接的更多信息.
尝试使用以下代码,记住这种情况总是使用AsyncTask:
私有类 Check_Loguin_Request 扩展了 AsyncTask {上下文 cx;字符串网址;列表BodyRequest_Elements;public Check_Loguin_Request(Context cx,String url, List ListOfValues){this.cx = cx;this.Url = url;this.BodyRequest_Elements = ListOfValues;}私有字符串 convertStreamToString(InputStream is) {BufferedReader reader = new BufferedReader(new InputStreamReader(is));StringBuilder sb = new StringBuilder();字符串行 = null;尝试 {while ((line = reader.readLine()) != null) {sb.append(line + "\n");}} catch (IOException e) {e.printStackTrace();} 最后 {尝试 {is.close();} catch (IOException e) {e.printStackTrace();}}返回 sb.toString();}@覆盖受保护的字符串 doInBackground(字符串...字符串){//声明变量DefaultHttpClient httpClient;HttpPost 请求 = 新的 HttpPost(url_Loguin);HttpResponse 响应;HttpParams httpParameters = new BasicHttpParams();httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);//以毫秒为单位设置超时,直到建立连接.//默认值为零,表示不使用超时.int timeoutConnection = 3000;HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置默认套接字超时(SO_TIMEOUT)//以毫秒为单位,这是等待数据的超时时间.int timeoutSocket = 5000;HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);httpClient = new DefaultHttpClient(httpParameters);尝试 {HttpEntity entity = new UrlEncodedFormEntity(BodyRequest_Elements);Request.setHeader(entity.getContentType());Request.setEntity(实体);响应 = httpClient.execute(Request);if(Response.getStatusLine().getStatusCode() == 200){String EntityResult = EntityUtils.toString(Response.getEntity());//HttpEntity EntityResult = Response.getEntity();//InputStream iStream = EntityResult.getContent();//JSONObject json = new JSONObject(convertStreamToString(iStream));EntityResult = EntityResult.replaceAll("[()]", "");JSONObject json = new JSONObject(EntityResult);String 结果 = json.optString("code").toString();返回结果;}别的{throw new RuntimeException("状态码无效");}}捕获(异常前){Log.getStackTraceString(ex);返回 ex.toString();}}}
I develop AndroidApps with AndroidStudio I start to do a simple HttpPost Request and I had a problems, all post that I could find do this:
private void CheckLoguin_Request(String User, String Pass){
//Declaration of variables
HttpClient httpClient = new DefaultHttpClient();
HttpPost Request = new HttpPost(url_Loguin);
HttpResponse Response;
List<NameValuePair> BodyRequest_Elements = new ArrayList<NameValuePair>();
BodyRequest_Elements.add(new BasicNameValuePair("user_name", User));
BodyRequest_Elements.add(new BasicNameValuePair("user_passwd", Pass));
Request.setEntity(new UrlEncodedFormEntity(BodyRequest_Elements));
Response = httpClient.execute(Request);
// writing response to log
Log.d("Http Response:", Response.toString());
}
But when I try to debugg App Android Studio give me a 2 errors in this lines:
new UrlEncodedFormEntity(BodyRequest_Elements) //Error:(40, 27) error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
Response = httpClient.execute(Request); //Error:(41, 38) error: unreported exception IOException; must be caught or declared to be thrown
It's possible I need install more libraries or support libraries? What I do bad? Anyone can helps me? Thanks in advance and sorry for my English!
PD1: If you need more info or code advise me!
Updated 2016
Using HttpURLConnection class we need to open BufferedWritter to insert our entity values as the following code:
//Declaration of variables
private List<NameValuePair> ListOfValues;
...
public Check_Loguin_Request(Context cx,String url, List<NameValuePair> ListOfValues)
{
this.cx = cx;
this.Url = url;
this.ListOfValues= ListOfValues;
}
@Override
protected String doInBackground(String... strings) {
//Declaration of variables
InputStream is = null;
String Result = "";
URL urll = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urll.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(Build_HttpBody(ListOfValues));
writer.flush();
writer.close();
os.close();
// Starts request
conn.connect();
int ResponseCode = conn.getResponseCode();
if (ResponseCode == 200) {
is = conn.getInputStream();
String EntityResult = ReadResponse_HttpURLConnection(is);
}
else {
throw new RuntimeException("Invalid Status Code");
}
}
Attention the DefaultHttpClient class is deprecated (2011)
For more info following this link.
Try to use this following code, remember for this case always use AsyncTask:
private class Check_Loguin_Request extends AsyncTask <String,Void,String>{
Context cx;
String Url;
List<NameValuePair> BodyRequest_Elements;
public Check_Loguin_Request(Context cx,String url, List<NameValuePair> ListOfValues)
{
this.cx = cx;
this.Url = url;
this.BodyRequest_Elements = ListOfValues;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Override
protected String doInBackground(String... strings) {
//Declaration of variables
DefaultHttpClient httpClient;
HttpPost Request = new HttpPost(url_Loguin);
HttpResponse Response;
HttpParams httpParameters = new BasicHttpParams();
httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient = new DefaultHttpClient(httpParameters);
try {
HttpEntity entity = new UrlEncodedFormEntity(BodyRequest_Elements);
Request.setHeader(entity.getContentType());
Request.setEntity(entity);
Response = httpClient.execute(Request);
if(Response.getStatusLine().getStatusCode() == 200){
String EntityResult = EntityUtils.toString(Response.getEntity());
//HttpEntity EntityResult = Response.getEntity();
//InputStream iStream = EntityResult.getContent();
//JSONObject json = new JSONObject(convertStreamToString(iStream));
EntityResult = EntityResult.replaceAll("[()]", "");
JSONObject json = new JSONObject(EntityResult);
String Result = json.optString("code").toString();
return Result;
}
else{
throw new RuntimeException("Invalid Status Code");
}
}
catch (Exception ex){
Log.getStackTraceString(ex);
return ex.toString();
}
}
}
这篇关于Build_HttpBody() 问题//httpPost.setEntity() - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!