i am getting this exception while i fetch data from an api that uses SOAP.
The response that i get is in Json format without an xml tag. i had also tried to parse the data using HttpResponse but it is not working...
W/System.err: org.xmlpull.v1.XmlPullParserException: Unexpected token (position:TEXT {
"Flag": 1,
...#6:2 in java.io.InputStreamReader#57e26d2)
at org.kxml2.io.KXmlParser.next(KXmlParser.java:432)
at org.kxml2.io.KXmlParser.next(KXmlParser.java:313)
at org.kxml2.io.KXmlParser.nextTag(KXmlParser.java:2048)
at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:126)
at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)
at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
at com.kritilims.kritilimsfieldtesting.MainLoginActivity$UserLoginTask.doInBackground(MainLoginActivity.java:224)
at com.kritilims.kritilimsfieldtesting.MainLoginActivity$UserLoginTask.doInBackground(MainLoginActivity.java:176)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
This is my code in asyncTask doInBackground. I dont Know what went wrong. The error is on the HttpTransportSe part.
#Override
protected String doInBackground(String... params) {
SoapObject request=new SoapObject(SOAP_NAMESPACE,SOAP_METHOD);
request.addProperty("labcode",mLabCode.getText().toString());
request.addProperty("username", mUserName.getText().toString());
request.addProperty("pass",mPasswordView.getText().toString());
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet=true;
try {
HttpTransportSE androidHttpTransportSE=new HttpTransportSE(URL);
androidHttpTransportSE.call(SOAP_ACTION,envelope);
SoapPrimitive soapPrimitive=(SoapPrimitive)envelope.getResponse();
result=soapPrimitive.toString();
Log.e("Test Result",""+result);
try {
JSONArray jsonArray=new JSONArray(result);
JSONObject jsonObject=jsonArray.getJSONObject(0);
strStatusID=jsonObject.getString("Flag");
labCode=jsonObject.getString("LabCode");
userName=jsonObject.getString("Username");
Log.e("Flag",""+strStatusID);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Related
I am working on a Gradle project with the Dropwizard framework can anyone help me how to upload an image using postman into the Dropwizard.
thanks in advance
i think you can use the following code that can upload the image using postman
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response simpleUpload(#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
return Response.ok(saveTOFile(uploadedInputStream, fileDetail)).type(MediaType.TEXT_PLAIN_TYPE).build();
}
private String saveTOFile(InputStream uploadedInputStream, FormDataContentDisposition fileDetail) {
final String UPLOAD_FOLDER="D://uploads/";
String filelocation = UPLOAD_FOLDER + fileDetail.getFileName();
File file = new File(filelocation);
try {
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (Exception e){
Response.status(Response.Status.BAD_REQUEST).entity("could not create Folder").type(MediaType.TEXT_PLAIN_TYPE).build();
}
try {
Files.copy(uploadedInputStream,file.toPath(),StandardCopyOption.REPLACE_EXISTING);
OutputStream out=new FileOutputStream("D://"+fileDetail.getFileName());
IOUtils.copyLarge(uploadedInputStream,out);
IOUtils.closeQuietly(out);
return "file copied to "+filelocation;
} catch (IOException e) {
e.printStackTrace();
return "file did not copied";
}
}
private void createFolderIfNotExists(String dirName)
throws SecurityException {
File theDir = new File(dirName);
if (!theDir.exists()) {
theDir.mkdir();
}
}
i am unable to upload file on xmpp using smack client android. slot.puturl() returns "https://localhost:7443/httpfileupload/27c97df7-dbbf-47ff-b19a-3ac624e51cf0/1.jpg"
HttpFileUploadManager manager = HttpFileUploadManager.getInstanceFor(mConnection);
try {
Slot slot = manager.requestSlot(path, 10000);
uploadFileToSlot(new File(path), slot);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
I got solution for after very deep research.
That HttpFileUploadManager is only for requesting slot from server.
Once you got slot request url upload file using httpclient or okhttpclient.
For okhttpclient:
You need to configure sslSocketFactory by mtm or certificatepinning.
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient().newBuilder();
SSLContext sslContext = JavaPinning.forPin(<PINNING_VALUE>);
okHttpClientBuilder.writeTimeout(5, TimeUnit.MINUTES)
.connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES);
okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), JavaPinning.trustManagerForPin(<PINNING_VALUE>));
OkHttpClient client = okHttpClientBuilder.build();
initiate okhttpclient and add file like.
Request request = new Request.Builder()
.url(slot.getPutUrl())
.put(RequestBody.create(MediaType.parse("application/octet-stream"), files))
.build();
Now lets begin to upload.
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
Log.i(log, "error " + e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
// Handle the error
Log.i(log, "errored " + response);
}
Log.i(log, "success " + response);
// Upload successful
}
});
Hope it helps you.
When /api/upload REST endpoint is accessed I have a UploadController that uses a service UploadService to upload a file to an ftp server with org.apache.commons.net.ftp.FTPClient. I would like to be able to send information back to the user if the ftp client was unable to connect or timed out, or successfully sent the file. I have some IOException handling, but I don't know how to turn that around and send it back to the front-end. Any help appreciated, thanks!
public void upload(InputStream inputStream) {
String filename = "file.txt"
client = new FTPClient();
try {
client.connect("ftpsite");
client.login("username", "password");
client.storeFile(filename, inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (inputStream!= null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return null;
}
You should throw a new Exception in your catch statement.
For example, you could create a RequestTimeoutException class:
#ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
public class RequestTimeoutException extends RuntimeException { }
and then throw it when need be:
catch (IOException ioe) {
//do some logging while you're at it
throw new RequestTimeoutException();
}
I have app that keep calling an api for json data, and pretty quickly i saw this 'Timeout waiting for connection from pool' exception, I googled around and found that's a connection leak caused by content not consumed, so i updated the code to close the inputstream after consume the jsondata, but still got those connection timeout exception, here is my code:
InputStream is = ApiUtil.getAsStream(Api.get(bookUrl).param("limit","500").param("bookId", bid).enable(Options.LongRunning), 3);
List<JsonBook> books = mapper.readValue(is, BOOK_TYPE);
is.close()
Api:
private JsonHttpClient client;
public APIForGet get(String endpoint) {
return new APIForGet(this.client, endpoint);
}
ApiUtil:
public static InputStream getAsStream(APIForGet get, Iterable<Long>retries) {
return get.asStream();
}
APIForGet:
private JsonHttpClient client;
public InputStream asStream() {
return this.client.getAsStream(this.hostname, this.port, this.endpoint, params, optionsArray());
}
JsonHttpClientImpl:
public InputStream getAsStream(Optional<String> host, Optional<Integer> port,String path, Multimap<String, String> param, Options ... options) {
HttpResponse reponse;
try {
response = request.execute();
if (response.isSuccessStatusCode()) {
return response.getContent();
}
} catch (Exception e) {
throw new Exception();
}
}
the wrapping logic here is kind of complicated, but eventually i think by closing the inputstream should work, any thoughts? Thanks!
try {
response = request.execute();
if (response.isSuccessStatusCode()) {
return response.getContent();
}
} catch (Exception e) {
throw new Exception();
}finally{
//TODO release conn or abort
}
I am getting data by http get through restful webservice hosted on IIS7 but when i am trying to put data i am having problem
MY code for put is as follows:
public Void put(String url, List<NameValuePair> data)
{
String response="";
HttpPut put = new HttpPut(url);
String dataString=data.toString();
HttpClient httpclient = new DefaultHttpClient();
try {
StringEntity entity = new StringEntity(dataString, "UTF-8");
entity.setContentType("x-www-form-urlencoded; charset=UTF-8");
put.setEntity(entity);
HttpResponse httpResponse1 = httpclient.execute(put);
StatusLine statusLine = httpResponse1.getStatusLine();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
The response i am getting is 405 Method not allowed, Can anybody tell me what is the problem?
You just have to uncheck webdave feature from the IIS menu which is in the window's features