I am trying to build an example of request for Skyscanner API in Java - but I am doing something wrong - the link for skyscanner API test: http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingQuickStart
Here is the test code I have so far - I get an "Internal Server Error".
Anyone can see what is incorrect in this example?
Thanks
package FLIGHTS;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Test {
public static final String HTTP_HEADER_X_APPLICATION = "X-Application";
public static final String HTTP_HEADER_X_AUTHENTICATION = "X-Authentication";
public static final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
public static final String HTTP_HEADER_ACCEPT = "Accept";
public static final String HTTP_HEADER_ACCEPT_CHARSET = "Accept-Charset";
public static String ENCODING_UTF8 = "UTF-8";
public static void main(String[] args) throws IOException {
HashMap<String, Object> params = new HashMap<>();
String API_KEY = "prtl6749387986743898559646983194";
// params.put("apiKey", API_KEY);
params.put("Country", "GB");
params.put("Currency", "GBP");
params.put("Locale", "en-GB");
params.put("Adults", 2);
params.put("Children", 2);
params.put("Infants", 0);
params.put("OriginPlace", 11235);
params.put("DestinationPlace", 13554);
params.put("OutboundDate", "2016-01-23");
params.put("InboundDate", "2016-01-30");
params.put("LocationSchema", "Default");
params.put("CabinClass", "Economy");
params.put("GroupPricing", true);
String url = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apikey="+API_KEY;
System.out.println(url);
HttpPost post = new HttpPost(url);
JsonrpcRequest request = new JsonrpcRequest();
request.setParams(params);
request.setMethod("POST");
request.setId("1");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX").create();
String jsonRequest = gson.toJson(request);
System.out.println(jsonRequest);
post.setHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded");
post.setHeader(HTTP_HEADER_ACCEPT, "application/json" );
post.setHeader(HTTP_HEADER_ACCEPT_CHARSET, ENCODING_UTF8 );
post.setEntity(new StringEntity(jsonRequest, ENCODING_UTF8));
HttpClient httpClient = new DefaultHttpClient();
JsonResponseHandler reqHandler = new JsonResponseHandler();
String resp = httpClient.execute(post, reqHandler);
System.out.println(resp);
}
static class JsonrpcRequest {
private String jsonrpc = "2.0";
private String method;
private String id;
private Map<String, Object> params;
public String getJsonrpc() {
return jsonrpc;
}
public void setJsonrpc(String jsonrpc) {
this.jsonrpc = jsonrpc;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Object> getParams() {
return Collections.unmodifiableMap(params);
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}
static class JsonResponseHandler implements ResponseHandler<String> {
#Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
return entity == null ? null : EntityUtils.toString(entity, ENCODING_UTF8);
}
}
}
I know it's an old question but I spent a lot of time to find an example that works in Java so I post here the solution that I've done. I used the HttpUrlConnection insted of the HttpClient and HttpPost classes.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class FlightsJava {
public static void main(String[] args) throws IOException {
String request = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty( "charset", "utf-8");
String urlParameters = "apiKey=YOUR_API_KEY&country=BR¤cy=BRL&locale=pt-BR&originplace=SDU&destinationplace=GRU&outbounddate=2016-09-23&locationschema=Iata&adults=1";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try{
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Header Fields : " + conn.getHeaderFields());
} catch (Exception e){
System.out.println(e);
}
}
}
Remember to change "YOUR_API_KEY" for your apiKey provided by skyscanner.
Hope it helps to anyone.
Related
I used httpclient 4.4 to send get and post request. and i just created a simpile wrapper of httpclient for easy use:
package com.u8.server.sdk;
import com.sun.net.httpserver.Headers;
import com.u8.server.log.Log;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.CookiePolicy;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Created by ant on 2015/10/12.
*/
public class UHttpAgent {
private int connectTimeout = 5000; //5s
private int socketTimeout = 5000; //5s
private int maxTotalConnections = 200;
private static UHttpAgent instance;
private CloseableHttpClient httpClient;
private UHttpAgent(){
}
public static UHttpAgent getInstance(){
if(instance == null){
instance = new UHttpAgent();
}
return instance;
}
public static UHttpAgent newInstance(){
return new UHttpAgent();
}
public String get(String url, Map params){
return get(url, null, params, "UTF-8");
}
public String post(String url, Map params){
return post(url, null, params, "UTF-8");
}
public String get(String url , Map headers, Map params, String encoding){
if(this.httpClient == null){
init();
}
String fullUrl = url;
String urlParams = parseGetParams(params, encoding);
if (urlParams != null)
{
if (url.contains("?"))
{
fullUrl = url + "&" + urlParams;
}
else
{
fullUrl = url + "?" + urlParams;
}
}
Log.d("the full url is "+ fullUrl);
HttpGet getReq = new HttpGet(fullUrl.trim());
getReq.setHeaders(parseHeaders(headers));
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String res = httpClient.execute(getReq, responseHandler);
return res;
} catch (Exception e) {
e.printStackTrace();
}finally {
getReq.releaseConnection();
}
return null;
}
public String post(String url, Map headers, Map params, String encoding){
List pairs = new ArrayList();
if(params != null){
for(String key : params.keySet()){
pairs.add(new BasicNameValuePair(key, params.get(key)));
}
}
return post(url, headers, new UrlEncodedFormEntity(pairs, Charset.forName(encoding)));
}
public String post(String url, Map headers, HttpEntity entity){
if(this.httpClient == null) {
init();
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(parseHeaders(headers));
httpPost.setEntity(entity);
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String body = httpClient.execute(httpPost, responseHandler);
return body;
} catch (IOException e) {
e.printStackTrace();
}finally {
httpPost.releaseConnection();
}
return null;
}
private Header[] parseHeaders(Map headers){
if(null == headers || headers.isEmpty()){
return getDefaultHeaders();
}
Header[] hs = new BasicHeader[headers.size()];
int i = 0;
for(String key : headers.keySet()){
hs[i] = new BasicHeader(key, headers.get(key));
i++;
}
return hs;
}
private Header[] getDefaultHeaders(){
Header[] hs = new BasicHeader[2];
hs[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
hs[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
return hs;
}
private String parseGetParams(Map data, String encoding){
if(data == null || data.size() keyItor = data.keySet().iterator();
while(keyItor.hasNext()){
String key = keyItor.next();
String val = data.get(key);
try {
result.append(key).append("=").append(URLEncoder.encode(val, encoding).replace("+", "%2B")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result.deleteCharAt(result.length() - 1).toString();
}
private void init(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setExpectContinueEnabled(true)
.setAuthenticationEnabled(true)
.build();
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
#Override
public boolean retryRequest(IOException e, int retryNum, HttpContext httpContext) {
if(retryNum >= 3){
return false;
}
if(e instanceof org.apache.http.NoHttpResponseException
|| e instanceof org.apache.http.client.ClientProtocolException
|| e instanceof java.net.SocketException){
return true;
}
return false;
}
};
try{
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
connMgr.setMaxTotal(maxTotalConnections);
connMgr.setDefaultMaxPerRoute((connMgr.getMaxTotal()));
HttpClientBuilder builder = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setSslcontext(sslContext)
.setConnectionManager(connMgr)
.setRetryHandler(retryHandler);
this.httpClient = builder.build();
}catch (Exception e){
e.printStackTrace();
}
}
public HttpClient getHttpClient(){
return this.httpClient;
}
public void destroy(){
if(this.httpClient != null){
try{
this.httpClient.close();
this.httpClient = null;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
when I use this class to send post request. something strange happened:
the first time, I send a post request to the server, it's ok
after a minutes, I send a same request to the server, it's ok too.
but after a few minutes, I send a same request, something wrong:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at org.apache.http.impl.conn.LoggingOutputStream.write(LoggingOutputStream.java:77)
at org.apache.http.impl.io.SessionOutputBufferImpl.streamWrite(SessionOutputBufferImpl.java:126)
at org.apache.http.impl.io.SessionOutputBufferImpl.flushBuffer(SessionOutputBufferImpl.java:138)
at org.apache.http.impl.io.SessionOutputBufferImpl.flush(SessionOutputBufferImpl.java:146)
at org.apache.http.impl.BHttpConnectionBase.doFlush(BHttpConnectionBase.java:175)
at org.apache.http.impl.DefaultBHttpClientConnection.flush(DefaultBHttpClientConnection.java:185)
at org.apache.http.impl.conn.CPoolProxy.flush(CPoolProxy.java:177)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:215)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:122)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:220)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:259)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:147)
at com.u8.server.sdk.baidu.BaiduSDK.verify(BaiduSDK.java:30)
at com.u8.server.web.UserAction.getLoginToken(UserAction.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
but then , I still send a same request to the server, it's ok again.
Every time I tried according to the above steps, The same thing happened.
Anyone can help me ? Thanks a lot.
The peer of your client is the server. So "Connection reset by peer" means the server reset the socket. Reset means forceably closed.
This might be because of a bug in the server. If you also wrote the server or servlet (as will be the case for a custom protocol), you need to examine the behaviour of the server to examine the cause of this. The log files of the server might provide clues.
If the server has protection against bisbehaving or malicious clients, the server might have reset the socket because it has classified your client as misbehaving. If you implemented the client protocol code it might be because of a bug in your protocol implementation. If you are using third party code for handling the communication protocol you might still be misusing it; for example by sending excessively large requests. It is not uncommon for HTTP servers to protect themselves against denial of service attacks by imposing maximum lengths for header fields and bodies, and to require that clients send data at a reasonably fast rate (without pausing for long periods). Your client might have fallen foul of these protections.
I am trying to send file using java, i have a existing python which is working which needs to be converted to java.
Below is my python code,
with io.open('test.text', 'rb') as f:
r = requests.request("POST",'http://my_url/post', data=f)
My java code
HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://my_url/post");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
Now i am not sure how to pass the file to the post request
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class PostFile {
public static void main(String[] aaa) throws URISyntaxException{
final URI uri = new URIBuilder("http://httpbin.org/post")
.build();
HttpPost request = new HttpPost(uri);
File f = new File("file.txt");
request.setEntity(new FileEntity(f));
CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
client.execute(request, new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse httpResponse) {
System.out.println("completed: " + httpResponse);
}
#Override
public void failed(Exception e) {
System.out.println("failed");
}
#Override
public void cancelled() {
System.out.println("cancelled");
}
});
}
}
Try this
Here is my code in TranslateAPI.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class TranslateAPI {
public static final String API_KEY = "pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a";
private static String request(String URL) throws IOException {
URL url = new URL(URL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inStream = urlConn.getInputStream();
String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();
System.setProperty("http.agent", "Chrome");
String agent = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("http.agent"));
inStream.close();
return recieved;
}
public static Map<String, String> getLangs() throws IOException {
String langs = request("https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=" + API_KEY + "&ui=en");
langs = langs.substring(langs.indexOf("langs")+7);
langs = langs.substring(0, langs.length()-1);
String[] splitLangs = langs.split(",");
Map<String, String> languages = new HashMap<String, String>();
for (String s : splitLangs) {
String[] s2 = s.split(":");
String key = s2[0].substring(1, s2[0].length()-1);
String value = s2[1].substring(1, s2[1].length()-1);
languages.put(key, value);
}
return languages;
}
public static String translate(String text, String sourceLang, String targetLang) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + API_KEY + "&text=" + text + "&lang=" + sourceLang + "-" + targetLang);
return response.substring(response.indexOf("text")+8, response.length()-3);
}
AND in workerthread.java:
String s=TranslateAPI.detectLanguage(abc);
System.out.println(s);
However,I am getting the follwing errror:
Server returned HTTP response code: 403 for URL: https://translate.yandex.net/api/v1.5/tr.json/detect?key=pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a&text=cat
Can you please help? Thanks in advance
You are getting a 401 Error thus Your API Key is Invalid,
You can always go to Yandex's Developers page to get a new one.
Its always great to publish your private API here :D
I am posting data by this POST method or by the first answer to this question, posting the data to a spring servlet configured with:
#RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String insert(String a) {
The servlet-method is called, but its parameter 'a' is null. Why?
Edit: The main method and the AsyncTask:
main method
ServerCaller serverCaller = new ServerCaller();
try {
serverCaller.execute(new URL("http://192.168.56.1:8080/SpringHibernateExample/insert"));
}
AsyncTask
package com.test.insert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
public class ServerCaller extends AsyncTask<URL, Integer, Long> {
#Override
protected Long doInBackground(URL... params1) {
try {
POST(params1[0].toString());
}
catch (Exception e) {
Log.realException(e);
throw new RuntimeException(e);
}
return 22l;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
public static String POST(String url) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "a");
jsonObject.accumulate("country", "b");
jsonObject.accumulate("twitter", "c");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
}
catch (Exception e) {
Log.e(e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
i think you pass a json object but you do not map it in spring.
In Spring you have to create a class ie CustomClass with properties name, country, twitter
public class CustomClass{
private String name;
private String country;
private String twitter;
//getters and setters should be here
}
then the code in Spring should look like this
#RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String insert(#RequestBody CustomClass cs) {
cs.getName();
Let me know if this helped
I used httpclient 4.4 to send get and post request. and i just created a simpile wrapper of httpclient for easy use:
package com.u8.server.sdk;
import com.sun.net.httpserver.Headers;
import com.u8.server.log.Log;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.CookiePolicy;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Created by ant on 2015/10/12.
*/
public class UHttpAgent {
private int connectTimeout = 5000; //5s
private int socketTimeout = 5000; //5s
private int maxTotalConnections = 200;
private static UHttpAgent instance;
private CloseableHttpClient httpClient;
private UHttpAgent(){
}
public static UHttpAgent getInstance(){
if(instance == null){
instance = new UHttpAgent();
}
return instance;
}
public static UHttpAgent newInstance(){
return new UHttpAgent();
}
public String get(String url, Map params){
return get(url, null, params, "UTF-8");
}
public String post(String url, Map params){
return post(url, null, params, "UTF-8");
}
public String get(String url , Map headers, Map params, String encoding){
if(this.httpClient == null){
init();
}
String fullUrl = url;
String urlParams = parseGetParams(params, encoding);
if (urlParams != null)
{
if (url.contains("?"))
{
fullUrl = url + "&" + urlParams;
}
else
{
fullUrl = url + "?" + urlParams;
}
}
Log.d("the full url is "+ fullUrl);
HttpGet getReq = new HttpGet(fullUrl.trim());
getReq.setHeaders(parseHeaders(headers));
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String res = httpClient.execute(getReq, responseHandler);
return res;
} catch (Exception e) {
e.printStackTrace();
}finally {
getReq.releaseConnection();
}
return null;
}
public String post(String url, Map headers, Map params, String encoding){
List pairs = new ArrayList();
if(params != null){
for(String key : params.keySet()){
pairs.add(new BasicNameValuePair(key, params.get(key)));
}
}
return post(url, headers, new UrlEncodedFormEntity(pairs, Charset.forName(encoding)));
}
public String post(String url, Map headers, HttpEntity entity){
if(this.httpClient == null) {
init();
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(parseHeaders(headers));
httpPost.setEntity(entity);
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String body = httpClient.execute(httpPost, responseHandler);
return body;
} catch (IOException e) {
e.printStackTrace();
}finally {
httpPost.releaseConnection();
}
return null;
}
private Header[] parseHeaders(Map headers){
if(null == headers || headers.isEmpty()){
return getDefaultHeaders();
}
Header[] hs = new BasicHeader[headers.size()];
int i = 0;
for(String key : headers.keySet()){
hs[i] = new BasicHeader(key, headers.get(key));
i++;
}
return hs;
}
private Header[] getDefaultHeaders(){
Header[] hs = new BasicHeader[2];
hs[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
hs[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
return hs;
}
private String parseGetParams(Map data, String encoding){
if(data == null || data.size() keyItor = data.keySet().iterator();
while(keyItor.hasNext()){
String key = keyItor.next();
String val = data.get(key);
try {
result.append(key).append("=").append(URLEncoder.encode(val, encoding).replace("+", "%2B")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result.deleteCharAt(result.length() - 1).toString();
}
private void init(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setExpectContinueEnabled(true)
.setAuthenticationEnabled(true)
.build();
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
#Override
public boolean retryRequest(IOException e, int retryNum, HttpContext httpContext) {
if(retryNum >= 3){
return false;
}
if(e instanceof org.apache.http.NoHttpResponseException
|| e instanceof org.apache.http.client.ClientProtocolException
|| e instanceof java.net.SocketException){
return true;
}
return false;
}
};
try{
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
connMgr.setMaxTotal(maxTotalConnections);
connMgr.setDefaultMaxPerRoute((connMgr.getMaxTotal()));
HttpClientBuilder builder = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setSslcontext(sslContext)
.setConnectionManager(connMgr)
.setRetryHandler(retryHandler);
this.httpClient = builder.build();
}catch (Exception e){
e.printStackTrace();
}
}
public HttpClient getHttpClient(){
return this.httpClient;
}
public void destroy(){
if(this.httpClient != null){
try{
this.httpClient.close();
this.httpClient = null;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
when I use this class to send post request. something strange happened:
the first time, I send a post request to the server, it's ok
after a minutes, I send a same request to the server, it's ok too.
but after a few minutes, I send a same request, something wrong:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at org.apache.http.impl.conn.LoggingOutputStream.write(LoggingOutputStream.java:77)
at org.apache.http.impl.io.SessionOutputBufferImpl.streamWrite(SessionOutputBufferImpl.java:126)
at org.apache.http.impl.io.SessionOutputBufferImpl.flushBuffer(SessionOutputBufferImpl.java:138)
at org.apache.http.impl.io.SessionOutputBufferImpl.flush(SessionOutputBufferImpl.java:146)
at org.apache.http.impl.BHttpConnectionBase.doFlush(BHttpConnectionBase.java:175)
at org.apache.http.impl.DefaultBHttpClientConnection.flush(DefaultBHttpClientConnection.java:185)
at org.apache.http.impl.conn.CPoolProxy.flush(CPoolProxy.java:177)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:215)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:122)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:220)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:259)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:147)
at com.u8.server.sdk.baidu.BaiduSDK.verify(BaiduSDK.java:30)
at com.u8.server.web.UserAction.getLoginToken(UserAction.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
but then , I still send a same request to the server, it's ok again.
Every time I tried according to the above steps, The same thing happened.
Anyone can help me ? Thanks a lot.
The peer of your client is the server. So "Connection reset by peer" means the server reset the socket. Reset means forceably closed.
This might be because of a bug in the server. If you also wrote the server or servlet (as will be the case for a custom protocol), you need to examine the behaviour of the server to examine the cause of this. The log files of the server might provide clues.
If the server has protection against bisbehaving or malicious clients, the server might have reset the socket because it has classified your client as misbehaving. If you implemented the client protocol code it might be because of a bug in your protocol implementation. If you are using third party code for handling the communication protocol you might still be misusing it; for example by sending excessively large requests. It is not uncommon for HTTP servers to protect themselves against denial of service attacks by imposing maximum lengths for header fields and bodies, and to require that clients send data at a reasonably fast rate (without pausing for long periods). Your client might have fallen foul of these protections.