Hi this is the web method to receive JSON and response JSON but the problem is this web method doesn't accept the gzip encoded request so how to make it to gzip acceptable web method?
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/pdf2doc")
public RPDOC postDocument(DPDF dpdf){
}
DPDF is the class
public class DPDF{
public String docid;
public String pdfdata;
}
This the client code with gzip Content encoding and throw exeption
String body = "{\"docid\": 1234, \"docdata\": \"test\"}";
HttpEntity httpEntity = EntityBuilder.create().setText(body)
.setContentEncoding("gzip")
.gzipCompress().build();
final String postUrl = serviceURL;
HttpUriRequest request = RequestBuilder.post(postUrl)
.setHeader(HttpHeaders.CONTENT_TYPE,
"application/json")
.setHeader(HttpHeaders.ACCEPT,
"application/json")
.setEntity(httpEntity)
.build();
String sResponse = null;
try (CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpclient.execute(request))
{
StatusLine sl = response.getStatusLine();
int statusCode = sl.getStatusCode();
System.out.println("HTTP Status: " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null)
{
sResponse = EntityUtils.toString(entity).trim();
System.out.println("HTTP Body:\n" + sResponse);
EntityUtils.consumeQuietly(entity);
}
}
catch (Exception e)
{
request.abort();
throw e;
}
}
catch (Exception e)
{
e.printStackTrace();
}
Related
I hava a java apache client written as :
public JSONObject createProject(String accessToken) throws PostEditException {
JSONObject jobj = new JSONObject();
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://"+HOST_TRANSPORT+"/api/projects/create");
try{
post.addHeader("Content-Type","application/json");
post.addHeader("Accept","application/json");
String authorizationValue = "Bearer "+accessToken;
post.addHeader("Authorization",authorizationValue);
HttpResponse response = client.execute(post);
if (response == null) {
System.out.println("this is null");
}
int code = response.getStatusLine().getStatusCode();
if (code != 200) {
HttpEntity entity = response.getEntity();
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = Charset.forName("UTF-8");
}
String errorBody = EntityUtils.toString(entity, charset);
log.info("createProject: Unable to process request. HTTP code: " + code + " responseBody: " + errorBody);
throw new PostEditException("createProject: Unable to process createProject request. HTTP code: " + code + " responseBody: " + errorBody);
} else {
HttpEntity entity = response.getEntity();
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = Charset.forName("UTF-8");
}
String taggedResult = EntityUtils.toString(entity, charset);
jobj = new JSONObject(taggedResult) ;
}
}catch (NoRouteToHostException re) {
log.error("createProject: unable to route to host."+re);
throw new PostEditException("createProject: unable to route to host.",re);
}catch (IOException ie) {
log.error("createProject: problem executing HTTP request."+ ie);
throw new PostEditException("createProject: problem executing HTTP request.",ie);
}catch (Exception e) {
log.error("createProject: an error occurred." +e );
throw new PostEditException("createProject: an error occurred",e);
} finally {
post.releaseConnection();
}
return jobj;
} //createProject
so , I am trying to write a test case to mock the HttpClient.
so I Wrote the Mockito test case as :
PowerMockito.mockStatic(HttpClientBuilder.class);
HttpClientBuilder builderMock = Mockito.mock(HttpClientBuilder.class);
PowerMockito.doReturn(builderMock).when(HttpClientBuilder.class, "create");
HttpClient clientMock = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse responseMock = Mockito.mock(CloseableHttpResponse.class);
Mockito.doReturn(clientMock).when(builderMock).build();
Mockito.doReturn(responseMock).when(clientMock).execute(Mockito.any());
classname obj= new classname();
Method m = classname.class.getDeclaredMethod("createProject", String.class);
JSONObject result =(JSONObject) m.invoke(obj,"accesstoken");
But when I debug the program, I see the real httpclient is created instead of the mocked one. How Do I create the mock httpclient so that I can mock the status and response as well.
I have to upload file to server whose API is a PUT request of content type as application/octet-stream. Below is my code
private void uploadVideo(File binaryFile, String url) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPut put = new HttpPut(url);
FileEntity reqEntity = new FileEntity(binaryFile, "application/octet-stream");
reqEntity.setContentType("application/octet-stream");
put.setEntity(reqEntity);
HttpResponse response = httpclient.execute(put);
HttpEntity entity = response.getEntity();
Log.d("INFO", "rcode:" + response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() - 200 >= 100)
throw new Exception("bad status code: " + response.getStatusLine().getStatusCode());
String responseString = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
I keep getting bad request but when I try from postman the file uploads perfectly fine. Any solutions?
bad status code: 400
I'm trying to do a soap request via a http post. According to this https://t4t.services.telenet.be/TelemeterService?wsdl that shows https://t4t.services.telenet.be/TelemeterService?xsd=1
I need to post a Id and password.
This is my request:
public static void main(String[] args) {
try {
callWebService("retrieveUsage");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void callWebService(String soapaction) throws IOException {
String body = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://www.telenet.be/TelemeterService/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ><SOAP-ENV:Body><mns1:RetrieveUsageRequest xmlns:mns1=\"http://www.telenet.be/TelemeterService/\"><UserId>test</UserId><Password>test</Password></mns1:RetrieveUsageRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>";
HttpPost httppost = new HttpPost("https://t4t.services.telenet.be/TelemeterService");
// Request parameters and other properties.
StringEntity stringentity = new StringEntity(body, "UTF-8");
stringentity.setChunked(true);
httppost.setEntity(stringentity);
httppost.addHeader("Accept", "text/xml");
httppost.addHeader("SOAPAction", soapaction);
//Execute and get the response.
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
}
System.out.println(strresponse);
System.out.println("Done");
}
I'm using apache http.
The strresponse is empty.
Is there something wrong with my code?
I am creating httpClient and when I send httpPost method, how can I attach a body to the httpRequest ??
public String httpPost(String URL, String BODY) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try {
response = httpclient.execute(httpPost); // get response from executing client
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return body.toString();
}
For example, the string is
" < html > < header > Header < /header> < body> I am body < /body> "
Where do I attach that string to the request message ?
Thank you :)
You can create a StringEntity, set it to the HttpPost object, and set the correct Content-Type:
StringEntity entity = new StringEntity("data=" + java.net.URLEncoder.encode(body, "utf-8"));
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
And then send your POST request as usual.
Have you tried httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ") before your try-catch?
I'm not entirely sure what "entity" refers to, but that's the best I can come up with from looking at the documentation here
I am creating a httpClient and I want to add certain header to my HttpGet request
My current code produces the following request.
GET /folder/index.html HTTP/1.0
Host: localhost:4444
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
What I want is to add another header (If-Modified-Since) in that request .
How can I do it?
Thank you :)
public String httpGet(String s) {
String url = s;
StringBuilder body = new StringBuilder();
httpclient = new DefaultHttpClient(); // create new httpClient
HttpGet httpGet = new HttpGet(url); // create new httpGet object
try {
response = httpclient.execute(httpGet); // execute httpGet
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// System.out.println(statusLine);
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection(); // stop connection
}
return body.toString(); // return the String
}
Use the setHeader() method on the HttpGet object like follows.
httpGet.setHeader("If-Modified-Since","11/26/2012");
I used this JavaDoc as a reference.
Use the setHeader() method on the HttpGet object like follows for the first one
httpGet.setHeader("If-Modified-Since","11/26/2012");
and then use addHeader() method on the HttpGet object like as follows for the second header.
httpGet.addHeader("If-Expires-On","11/26/2014");