Send file using POST from a Java - java

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

Related

Mock an instance method call of another class that takes a URL and File object and writes a file to a HTTP connection

I'm trying to write UTs for a file called DocumentStoreAccessor.java. Here is the class below:
package com.company.main.accessor;
import com.company.main.dagger.component.AccessorComponent;
import com.company.main.dagger.component.DaggerAccessorComponent;
import com.company.main.util.aws.s3.AWSS3Util;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
#Slf4j
#RequiredArgsConstructor
public class DocumentStoreAccessor {
private final DocumentStore documentStoreClient; //Comes from Dagger
public DocumentStoreAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.documentStoreClient = accessorComponent.provideDocumentStoreClient();
}
private int putContentsIntoS3(CreateUploadS3UrlResult createUploadS3UrlResponse,
#NonNull File file) {
int uploadStatusCode = 0;
try {
URL url = new URL(createUploadS3UrlResponse.getS3Url());
uploadStatusCode = new AWSS3Util().upload(url, file); //Instance comes from a util class
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uploadStatusCode;
}
public String uploadFile(File file, DocumentFileExtension fileExtension) throws Exception {
String documentId = null;
CreateUploadS3UrlResult createUploadS3Urlresult = documentStoreClient.createUploadS3Url(new CreateUploadS3UrlRequest());
int putContentsStatusCode = putContentsIntoS3(createUploadS3Urlresult, file);
if (putContentsStatusCode == 200) {
CreateDocumentRequest createDocumentRequest = new CreateDocumentRequest()
CreateDocumentResult document = documentStoreClient.createDocument(createDocumentRequest);
documentId = document.getDocumentId();
} else {
throw new Exception("Status code is: " + putContentsStatusCode);
}
return documentId;
}
}
Inside this file I do new AWSS3Util().upload(url, file).
And here is the AWSS3Util.java
package com.company.main.util.aws.s3;
import com.company.main.exception.DataAccessException;
import com.company.main.exception.RetriableDataAccessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
#Slf4j
#AllArgsConstructor
#Builder
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
final InputStream inputStream = new FileInputStream(file);
final Reader fileReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(fileReader);
HttpURLConnection connection = null;
int responseCode = 0;
try {
// Create the connection and use it to upload the new object using the pre-signed URL.
connection = create(url);
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
String st;
while ((st = br.readLine()) != null) {
out.write(st);
}
out.close();
responseCode = connection.getResponseCode();
} catch (IOException e) {
throw new RetriableDataAccessException(String.format("S3 upload request failed with request: %s", url.toString()), e);
} finally {
inputStream.close();
fileReader.close();
br.close();
}
return responseCode;
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
I want to make new AWSS3Util().upload(url, file) return a 200..
I'm unable to do so.. I keep getting a NullPointerException. Here is what I have for the past day:
package com.company.main.accessor;
import com.company.main.util.aws.s3.AWSS3Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#ExtendWith(MockitoExtension.class)
public class DocumentStoreAccessorTest {
#Mock
private DocumentStore mockDocumentStoreClient;
#Mock
private HttpURLConnection httpURLConnection;
#Mock
private OutputStream outputStream;
#InjectMocks
private DocumentStoreAccessor classUnderTest;
private URL url;
private AWSS3Util awss3Util;
private CreateUploadS3UrlRequest dummyCreateUploadS3UrlRequest;
private CreateUploadS3UrlResult dummyCreateUploadS3UrlResult;
private CreateDocumentRequest dummyCreateDocumentRequest;
private CreateDocumentResult dummyCreateDocumentResult;
#BeforeEach
void setUp() throws IOException {
awss3Util = new AWSS3Util();
url = getMockUrl(httpURLConnection);
dummyCreateUploadS3UrlRequest = new CreateUploadS3UrlRequest();
dummyCreateUploadS3UrlResult = new CreateUploadS3UrlResult().withS3Url("http://foo.io://:99");
dummyCreateDocumentRequest = new CreateDocumentRequest();
dummyCreateDocumentResult = new CreateDocumentResult().withDocumentId("foo");
}
#Test
void uploadSuccess() throws IOException {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
AWSS3Util aSpy = Mockito.spy(awss3Util);
Mockito.when(aSpy.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
private File getDataToUpload() {
return new File("TestFileName.xlsx");
}
/**
* We cannot directly use Mockito to mock URL. This helper method, helps us to create the mock url.
* <p>
* https://stackoverflow.com/questions/565535/mocking-a-url-in-java
*/
private URL getMockUrl(HttpURLConnection httpURLConnection) throws IOException {
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return httpURLConnection;
}
};
final URL url = new URL("http://foo.io", "foo.io", 80, "", handler);
return url;
}
}
I'm unable to mock the URL class, so I followed a another Stackoverflow post..
The AWSS3Util cannot come through Dagger, it is a util class that we're all using so this must not change.
I'm not sure if I'm going in the right direction.. I've tried "spying" on that AWSS3Util class. I want this method to return a 200 or any status code of my choice to cover them in UTs by asserting a String return as seen in the example below
I can change the the upload method inside AWSS3Util to static if it helps UTs
Cannot use PowerMockito (this is a last resort)
Try incorporating Yan's comments:
#Test
void verifyCreateUploadS3UrlInvocation() throws Exception {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
when(httpURLConnection.getOutputStream()).thenReturn(outputStream);
when(httpURLConnection.getResponseCode()).thenReturn(200);
when(awss3Util.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
I get a 405 thrown when I specifically want it to send a 200, and therefore java.lang.Exception: Status code is: 405 thrown from my function.
Firstly I would change a little bit AWSS3Util, because reading binary files as string can lead to very interesting results.
import lombok.NonNull;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
HttpURLConnection connection = create(url);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
try (BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream())) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return connection.getResponseCode();
}
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
Test for upload method could be like this:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
#Test
public void test() throws IOException {
final HttpURLConnection mockUrlCon = mock(HttpURLConnection .class);
URLStreamHandler stubUrlHandler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return mockUrlCon;
}
};
URL url = new URL("http://foo.io", "foo.io", 80, "", stubUrlHandler);
when(mockUrlCon.getResponseCode()).thenReturn(200);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
when(mockUrlCon.getOutputStream()).thenReturn(outputStream);
File file = new File("c:\\anyFile.png");
int responseCode = new AWSS3Util().upload(url, file);
assertEquals(200, responseCode);
byte[] expectedBytes = Files.readAllBytes(file.toPath());
byte[] actualBytes = outputStream.toByteArray();
assertArrayEquals(expectedBytes, actualBytes);
}
}
I had to violate the second rule - I had to DependencyInject it via Dagger
package com.company.main.dagger.module;
import com.company.main.util.aws.s3.AWSS3Util;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
#Module
public class AWSS3UtilModule {
#Provides
#Singleton
public static AWSS3Util provideAwss3Util() {
return new AWSS3Util();
}
}
and then in my component
import javax.inject.Singleton;
#Singleton
#Component(modules = {
ShipDocsDMSAccessorModule.class,
AWSS3UtilModule.class
})
public interface AccessorComponent {
ShipDocsDMS provideShipDocsDMSClient();
AWSS3Util provideAwss3Util();
}
and then in my main class
#Slf4j
#RequiredArgsConstructor
public class ShipDocsDMSAccessor {
private final ShipDocsDMS shipDocsDMSClient;
private final AWSS3Util awss3Util;
public ShipDocsDMSAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.shipDocsDMSClient = accessorComponent.provideShipDocsDMSClient();
this.awss3Util = accessorComponent.provideAwss3Util();
}
.
.
.
.
and then in my test, I can freely mock AWSS3Util dependency and carry ahead and force out the required response.

JAVA- generate scheduled JSON

I started with this :http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
and created a JSON on localhost:8080...
I am not sure if there is any way to generate new Json every 3 or 5 second. for example just add one digit to new JSON every 3 sec.
#Path("/LNU.se")
public class EntryPoint {
#GET
#Path("get")
#Produces(MediaType.TEXT_PLAIN)
public String test() {
return "mahdi Test";
}
#POST
#Path("post")
#Consumes(MediaType.TEXT_PLAIN)
public Response postTest(Track track){
String resault = " the track is saved mahdi: "+ track;
return Response.status(201).entity(resault).build();
}
}
and another class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter( "jersey.config.server.provider.classnames", EntryPoint.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open your browser on http://localhost:8080/LNU.se/get");
jettyServer.join();
} catch (Exception e)
{
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
======================
UPDATE: -->
My server is:
package rest;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class RestServer {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
Calculator.class.getCanonicalName());
try {
jettyServer.start();
System.out.println(" open the browser on http://localhost:8080/calculator/squareRoot?input=16");
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
and this class:
package rest;
import java.awt.event.ItemEvent;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
#Path("calculator")
public class Calculator {
Result ress = new Result("mahdi84");
public static String resul1;
#GET
#Path("mahdi")
#Produces(MediaType.APPLICATION_JSON)
public Result mahdi(){
JSONObject json = new JSONObject();
json.put("validTime", "2016-02-24T11:00:00Z");
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("mcc", resul1);
obj.put("temprature", resul1+1);
obj.put("Humidity", resul1+10);
jsonArray.add(obj);
json.put("\n JSONdata --> ", jsonArray);
ress.setInput(Double.parseDouble(resul1));
ress.setOutput(Double.parseDouble(resul1));
ress.setTestVar(resul1);
ress.setTestVar2(json);
return ress;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
resul1= data;
return Response.status(201).entity(result).build();
}
static class Result{
double input;
double output;
String action;
Object testVar;
JSONObject testVar2;
public Result(){}
public JSONObject getTestVar2() {
return testVar2;
}
public void setTestVar2(JSONObject testVar2) {
this.testVar2 = testVar2;
}
public Object getTestVar() {
return testVar;
}
public void setTestVar(Object testVar) {
this.testVar = testVar;
}
public Result(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public double getInput() {
return input;
}
public void setInput(double input) {
this.input = input;
}
public double getOutput() {
return output;
}
public void setOutput(double output) {
this.output = output;
}
}
}
and my client is:
import java.util.Timer;
import java.util.TimerTask;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost extends TimerTask{
public int cuntr = 0;
public static void main(String[] args) {
TimerTask mytask = new JerseyClientPost();
Timer timer = new Timer();
timer.schedule(mytask, 1000, 1000);
}
#Override
public void run() {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/calculator/post");
String input = Integer.toString(cuntr++);
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
the client will post to the server every 1 sec and the server will generate new JSON on "http://localhost:8080/calculator/mahdi"
when i try to read from "http://localhost:8080/calculator/mahdi" by apache http1.1 in another program :
package HttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public static void main(String[] args) throws Exception{
HttpGet requset = new HttpGet("http://localhost:8080/calculator/mahdi");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(requset);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
System.out.println("Reading began ... ");
while (true) {
String line = br.readLine();
if (line != null && !line.isEmpty()) {
System.out.println(line);
}
}
}
}
edit:
thank you I did that by using TImeTask class
it only print the first JSON! but when I refresh the weblink, it is updating on browser.
would you please correct me if I am wrong? I want to see the stream of JSON on MyHttpClient, but it only shows the first JSON!
I think you are mixing things. The server should only be a server, and not extend TimerTask. The client should call the server at a specific intervall
Do the follwing:
Test your server in a web-browser. Make sure that it will respond.
Write a client either in Java or javascript If you are using Java
the client should have a http-client.
The client should hava a timertask calling the the server at a specific intervall

Skyscanner API example in Java

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&currency=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.

Read HTTP POST from mobile in java

I have iOS Swift code, which sends a POST request to server. If i send this code directly to apple server i get response back with proper data. But when i send this to my server, server could not get the body of the HTTP POST.
I have no idea whether this issue is related to client side or server side.
Here is the Swift code.
func validateReceipt(completion : (status : Bool) -> ()) {
let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL!
if NSFileManager.defaultManager().fileExistsAtPath(receiptUrl.path!)
{
if let receipt : NSData = NSData(contentsOfURL: receiptUrl)
{
let receiptdata: NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
let dict = ["receipt-data" : receiptdata]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
let request = NSMutableURLRequest(URL: NSURL(string: ReceiptURL.MAIN_SERVER.rawValue)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = jsonData
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let dataR = data
{
self.handleData(dataR, completion: { status in
completion(status: status)
})
}
})
task.resume()
}
else
{
completion(status: false)
}
}
else
{
completion(status: false)
}
}
and here is my Java code in server side, there are two Java classes which take care of this
MyRequestWrapper.Java
package webservice;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[100000];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
And here is the another class.
GetResult.Java
package webservice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
#Path("/service")
public class GetResult {
static Logger logger = Logger.getLogger(GetResult.class);
// #Produces("application/json; charset=UTF-8")
//#Produces("text/plain")
#POST
#Produces (MediaType.APPLICATION_JSON)
public Response inapp(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws Exception {
System.out.println("response===" + response);
System.out.println("Request-Header===" + request.getHeader("receipt-data"));
System.out.println("Request===" + request.getParameter("receipt-data"));
// System.out.println("Request==="+request.getReader());
// reader(request,response);
// getBody(request);
doFilter(request,response);
String result = "";
result = " " /* jsonObject */;
return Response.status(200).entity(result).build();
}
We could get the client IP and client Port from this request but unable to get the body. In production also we could not get the body. Some Java developers told me that you cant directly get the raw bytes in Java, i don't know about this.
Somebody please take a look at this, and tell me what i am doing wrong.
You may have to explicitly set the content type of the input post body you send to the server. This can be achieved as follows:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Set the content type after setting the http method and son data to the request object( NSMutableURLRequest object)
This may help you!
Edited:
Actually the header field name is "Content-Type".

get XML from server by URL in AsyncTask and return response to UI

I try to get xml from server in async task, but my doInBackground method returns me NULL. Where is my mistake? And how I can send result to UI?
Here is all classes
I have this code for getting xml from server:
package classes;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by Mikhail on 28.03.2015.
*/
public class GetXMLFromServer {
InputStreamReader reader;
public GetXMLFromServer(){
//reader = null;
}
public InputStreamReader getReaderWithXML(String url){
GetXMlTask task = new GetXMlTask();
task.execute(url);
return reader;
}
public void setReader(InputStreamReader newReader){
this.reader = newReader;
}
class GetXMlTask extends AsyncTask<String, Integer, InputStreamReader>{
#Override
protected InputStreamReader doInBackground(String... params) {
InputStreamReader iStream = null;
try {
iStream = new InputStreamReader(getUrlData(params[0]));
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return iStream;
}
#Override
protected void onPostExecute(InputStreamReader inputStreamReader) {
super.onPostExecute(inputStreamReader);
setReader(inputStreamReader);
}
public InputStream getUrlData(String urlString) throws URISyntaxException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(String.valueOf(new URL(urlString)));
HttpResponse res = client.execute(method);
StatusLine status = res.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d("APP", "HTTP error.Invalid server status code: " + res.getStatusLine());
}
return res.getEntity().getContent();
}
}
}
You have a good example how to use async task here.
Please check it!
The returning is in onPostExecute method.
To send the result to UI use OnPostExecute do call a static method of your UI class.
protected void onPostExecute(Long result) {
YourUIFragmentORActivity.showResult(result);
showDialog("Downloaded " + result + " bytes");
}

Categories