In the process of requesting data through httpclient or URLs, inevitably will appear garbled problem, the author in the project development process encountered this problem, on the Internet to find a pile of data, are in the receiving end to solve the problem, ignoring the sender of the coding problem, so in the receiving end all methods are used or not, Now put the solution to the industry, hoping to help meet the same problem friends. Directly on the code
One, the receiving end
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.ParseException;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.util.EntityUtils;
Import org.json.JSONException;
Import Org.json.JSONObject;
public static jsonobject post (String URL)
{
HttpClient httpclient = new Defaulthttpclient ();
HttpPost HttpPost = new HttpPost (URL);
Httppost.setheader ("Content-type", "application/x-www-form-urlencoded");
try {
HttpResponse HttpResponse = Httpclient.execute (HttpPost);
InputStream instream = httpresponse.getentity (). getcontent ();
BufferedReader reader = new BufferedReader (new InputStreamReader (instream, "utf-8")); Please note the code here
StringBuilder strber = new StringBuilder ();
String line = null;
while (line = Reader.readline ())!= null)
Strber.append (line);
Instream.close ();
Jsonobject jsonobj = new Jsonobject (strber.tostring ());
return jsonobj;
catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
return null;
}
return null;
}
Two, send the end
This is SPRINGMVC.
Import org.springframework.http.HttpEntity;
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;
Import org.springframework.http.ResponseEntity;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RestController;
@RequestMapping ("/userinfo")
Public httpentity UserInfo (HttpServletRequest request) {
String js = "This is where the HTML text is to be improved";
Httpheaders headers = new Httpheaders ();
MEDIATYPE mediatype = new mediatype ("text", "HTML", Charset.forname ("Utf-8"));
Headers.setcontenttype (mediatype);
return new Responseentity<string> (Js,headers, Httpstatus.ok);
}