Upload File: Comsuming WCF Web Service Using Java - java

I have a WCF Web Service (.NET C#). And I want to consume that service by java client application.
I have a following code using that I am successfully able to connect with the Web Service. But now I am facing problem with uploadFile method.
When I am passing string to the request entity then it call the web service method but as I passed/set FileInputStream RequestEntity then it throw exception ...
Connection reset by peer: socket write error
My Java Client Code is as following....
Please ignore: logging is not added here...
public void consumeService(){
String sXML = null;
String sURI = URI + "/upload";
sXML = item;
HashMap<String, String> header = new HashMap();
header.put("Content-type", "application/x-www-form-urlencoded");
File file = new File("C:\\Users\\admin\\Desktop\\P1130503.JPG");
try {
RequestEntity requestEntity= new InputStreamRequestEntity(
new FileInputStream(sFile), InputStreamRequestEntity.CONTENT_LENGTH_AUTO);
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
headers.addHeader(key, value);
}
} catch (Exception ex) {
Logger.getLogger(C3Service.class.getName()).log(Level.SEVERE, null, ex);
}
HttpMethodBase httpPostRequest = new PostMethod(url + buildParams());
HttpClient client = new HttpClient();
try {
// add headers
Iterator it = headers.entrySet().iterator();
while (it.hasNext()) {
Entry header = (Entry) it.next();
httpPostRequest.addRequestHeader((String) header.getKey(), (String) header.getValue());
}
((PostMethod) httpPostRequest).setRequestEntity(requestEntity);
try {
respCode = client.executeMethod(httpPostRequest);
System.out.println("Response Code "+respCode);
response = httpPostRequest.getResponseBodyAsString();
this.responsePhrase = httpPostRequest.getStatusText();
System.out.println("Response "+response);
System.out.println("Response Phase "+responsePhrase);
}catch(Exception ex){
System.out.println("ErrorS "+ex.toString());
} finally {
// resp.close();
httpPostRequest.releaseConnection();
}
}catch(Exception ex){
System.out.println("ErrorD "+ex.toString());
}
finally {
//client.c
}
}
NOTE: when I passed string and set StringRequestEntity then it working file.
new StringRequestEntity(statusAsXml, "text/plain", Constants.DEFAULT_ENCODING)
C# CODE
IService
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "upload")]
bool upload(Stream relativePath);

I got my answer. It was the matter of assigning valid content type. I was setting content type
header.put("Content-type", "application/x-www-form-urlencoded");
After using following content-type, I am able to upload file successfully
httpConn.setRequestProperty("Content-Type","multipart/form-data");

Related

How to make HTTPS request in java

I am trying to fetch data from api which use https protocol,
but the problem is, I dont know how java work with https, what are the steps the one should follow.
My Program is working correctly on http but i need to convert this into https.
here is my current code ->
var url = "https://api.hubapi.com/contacts/v1/lists/all/contacts/all";
String authorizationHeader = "Bearer " + context.getProperty(token).getValue();
var client = HttpClient.newBuilder().build();
boolean whichOne = currentTimeUTC.isBefore(expireIn);
if (whichOne) {
var request = HttpRequest.newBuilder().GET().header("Authorization", authorizationHeader)
.header("Content-Type", "application/json").uri(URI.create(url)).build();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
flowFile = session.write(flowFile, (rawIn, rawOut) -> {
try(final InputStream in = new BufferedInputStream(rawIn);
final OutputStream out = new BufferedOutputStream(rawOut)) {
out.write(response.body().getBytes());
} catch (Exception e) {
System.out.println("Error -> "+e);
}
});
} catch (Exception e) {}
can any one help me...

http post request return 400

I'm using HTTP post method to call Gitlab API which in return it gives me 400 response code.
I have tested the gitlab api with postman with providing propers headers and content body as JSON.
it worked fine and. ( I use gitlab create branch api )
I have debugged the application using eclipse and , there is some specific line which gave me null
I'm using apache http client 4.5.5 to handle http requests.
this is my first method to create a branch
public HttpResponse createBranch(String projectId, String branchName, String ref) {
// url is ok, i debugged it
String url = this.API_BASE_URL + projectId + "/repository/branches";
//branchName = "uifix branch";
//ref = "master";
JSONObject obj = new JSONObject();
try {
obj.put("branch", branchName);
obj.put("ref", ref);
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> headerParams = new HashMap<String, String>();
headerParams.put("Private-Token", PAT);
headerParams.put("Content-Type", "application/json; utf-8");
headerParams.put("Accept", "application/json");
return HttpUtility.httpPostForResourceCreation(url, headerParams, obj.toString());
}
then will call the following method which is in httputlity class.
public static HttpResponse httpPostForResourceCreation(String url, Map<String, String> headerParam, String body) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body, ContentType.APPLICATION_JSON);
for (Map.Entry<String, String> entry : headerParam.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
request.setEntity(params); // I think problem is here. when I debugged it , it shows null.
return execute(request);
}
then will call the last method
private static HttpResponse execute(HttpRequestBase request) {
HttpClient httpClient = HttpUtility.buildHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response.getStatusLine().getStatusCode() == 201) {
System.out.println("resource successfully created: " + 201);
} else {
System.out.println("resource creation failed: " + response.getStatusLine().getStatusCode());
}
return response;
}
expected result should be "resource successfully created: + 201"
instead of I'm getting "resource creation failed: 400"
here I attached my request object content
so, what I'm missing here ? Any help would be appreciated.

How to correctly write POST request for a restheart on java

I am using restheart to provide a restful interface to mongodb. Get method is working good, I'm getting data from database in respons. But in this instance I'm trying to implementing POST request to write data in base. I'm running following code but I'm getting response with code 415 unsupported media type. My test base db1 have one collection testcoll where I'm trying to write a document with fields "name" and "rating"
public class PostMethodJava {
public static void main(String[] args) throws IOException {
URL url;
try {
url = new URL("http://127.0.0.1:8080/db1/testcoll/");
//url = new URL("http://google.com/");
} catch (Exception et) {
System.out.println("Data URL is broken");
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:12345678";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
//hc.setDoInput(true);
hc.setDoOutput(true); //<== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("POST");
//hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
String parameter = "mame=test1&rating=temp";
int plength = parameter.length();
byte[] pdata = parameter.getBytes(StandardCharsets.UTF_8);
try (DataOutputStream out = new DataOutputStream(hc.getOutputStream())){
out.write(pdata);
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
}
}
What is wrong and how can I fix it?
Adding a line:
hc.setRequestProperty("Content-Type","application/json");
and writing the string:
String parameter = "{\"name\":\"doubleabc\",\"rating\":\"allright\"}";
fixed my problem.

How to call Json Post request with queryparam on client side?

I wrote both Service and CLient part of application. I tested my service with "Postman" application and it is working fine with url = http://192.168.2.50:8084/FaceBusinessService/webresources/service/login?phone=123456789&password=1234
However when I try to call it on my Android Application it is not working. While debuging on service side I see that phone and password parameters are NULL.
Here is my service side :
#Path("login")
#POST
#Produces("application/json")
public String postJson(#QueryParam("phone")String phone, #QueryParam("password") String password) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(phone, password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}
Here is my android app side :
private UserInfo loginUser(String phone, String password) {
UserInfo userInfo = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.2.27:8084/FaceBusinessService/webresources/service/login");
try {
/*
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("phone", new StringBody(phone));
entity.addPart("password", new StringBody(password));
post.setEntity(entity);
*/
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Log.d(TAG, "POST String: " + post.toString());
try {
HttpResponse response = httpClient.execute(post);
if (response.getEntity().getContentLength() > 0) {
String json_string = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(json_string);
// TODO
return userInfo;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return null;
}
I tried both MultipartEntity and NameValuePair but none of them worked. Could you give me idea how to handle this issue?
Note that when testing with Postman you passed parameters (user name and password) as part of the URL (URL encoded), which can be directly retrieved on the server side. (you don't even need a POST request for this). Your objects are passed as string objects, not JSON objects.
In your client code , the URL is different because you're encoding the parameters as part of the POST request entity (payload). The parameters are packaged inside of the request/message body and not in the URL.
Now since your URL doesn't have the parameters, you should retrieve them by deserializing the request (desderialize the JSON request into a UserInfo object).
Note that you should rewrite your server side code completely as it should accept a application/JSON object but it apparently should return/produce a String object (plain/text or application/HTML).
I'm not familiar with GSON but your code might look something like
#Path("login")
#POST
#Produces("text/plain")
#Consumes("application/json")
public String postJson(UserInfo ui) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(ui.phone, ui.password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}

HTTP POST method returning status code 404

When I execute an API through following method, I always get 404 as response code.
private void execute() throws IllegalStateException, IOException, NoSuchAlgorithmException {
Map<String, String> comment = new HashMap<String, String>();
comment.put("accounts-groups", "customers/enterprise");
comment.put("companyType", "customer");
comment.put("companyName", "Test");
String json = new GsonBuilder().create().toJson(comment, Map.class);
Log.i(TAG, "json : "+json);
HttpResponse response = makeRequest(URL, json);
/*Checking response */
if(response != null) {
InputStream inputStream = response.getEntity().getContent(); //Get the data in the entity
int statusCode = response.getStatusLine().getStatusCode();
Log.i(TAG, "statusCode : "+statusCode);
String result;
// convert inputstream to string
if(inputStream != null)
result = convertStreamToString(inputStream);
else
result = "Did not work!";
Log.i(TAG, "result : "+result);
}
}
private HttpResponse makeRequest(String uri, String json) throws NoSuchAlgorithmException {
Log.i(TAG, "uri : "+uri);
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json, HTTP.UTF_8));
long timestamp = System.currentTimeMillis();
String signatureKey = PRIVATE_KEY + timestamp;
byte[] bytesOfMessage = signatureKey.getBytes(HTTP.UTF_8);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
char[] signature = Hex.encodeHex(thedigest);
String finalSignature = String.valueOf(signature);
Log.i(TAG, "finalSignature : "+finalSignature);
httpPost.setHeader("Timestamp", ""+timestamp);
httpPost.setHeader("Api_token", API_TOKEN);
httpPost.setHeader("Signature" , finalSignature);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I am not getting where am I going wrong. Can anybody please help me out?
from wiki:
The 404 or Not Found error message is a HTTP standard response code
indicating that the client was able to communicate with the server,
but the server could not find what was requested.
so, your code is OK, but server cannot find resource you are looking for. Double check if your url is correct.
how to pass request through fiddler proxy for debugging purposes:
HttpParams params = new BasicHttpParams();
// ....
HttpHost proxy = new HttpHost("192.168.1.12", 8888); // IP to your PC with fiddler proxy
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
// use params as a second parameter to: following constructor:
// public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)
I was getting 404 for POST requests because mod_headers module of Apache 2 server was not enabled. If that happens you can enable it with:
sudo a2enmod headers
and then restart apache:
sudo service apache2 restart

Categories

Resources