I'm modifying some working code to work with a different provider's API (we are switching helpdesk providers).
I am trying to look at the xml coming back to see if I am even on the right track, but all I see coming back is gibberish. I've looked at this question but can't figure out how those answers might apply to my situation.
If I remember correctly, when I used the other API I was able to read the xml coming back in the console here:
while ((line = br.readLine()) != null) {
System.out.println(line);
}
My question is: Is there a way I can read the stream differently so that I can read the xml that is coming back or do I have another problem?
I'm pretty new to this so any thoughts are appreciated. Further details are below.
Code:
package com.google.gwt.HelpDeskTest.server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.google.gwt.HelpDeskTest.shared.HelpDeskTestException;
#SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
HelpDeskTestService {
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
final String serverPath= "https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails";
System.out.println(serverPath);
final String serverParameters= "<?xml version=%221.0%22 encoding=%22utf-16%22?>" +
"<GetTicketAction xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22 xmlns:xsd=%22http://www.w3.org/2001/XMLSchema%22>" +
"<CompanyName>xxxxxx</CompanyName><IntegrationLoginId>xxxxxxx</IntegrationLoginId><IntegrationPassword>xxxxxx</IntegrationPassword>" +
"<SrServiceRecid>1921</SrServiceRecid></GetTicketAction>";
System.out.println(serverParameters);
//Open HttpURLConnection:
URL url = new URL(serverPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-16");
connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
connection.setUseCaches (false);
//connection.setChunkedStreamingMode(0);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(serverParameters);
wr.flush();
wr.close();
//process response - need to get xml response back.
//this was the working line of code:
InputStream stream = connection.getInputStream();
//put output stream into a string
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String result = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
result+= line;
}
br.close();
connection.disconnect();
System.out.println(result);
return result;
} catch (final Exception e) {
System.out.println(e.getMessage());
throw new HelpDeskTestException();
//handle timeout error
}
}
}
This is the xml I'm attempting to send. I've tested it through the company's API tester and know that it works, and responds by sending xml.
<?xml version="1.0" encoding="utf-16"?>
<GetTicketAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>xxxxxx</CompanyName>
<IntegrationLoginId>xxxxxx</IntegrationLoginId>
<IntegrationPassword>xxxxx</IntegrationPassword>
<SrServiceRecid>1921</SrServiceRecid>
</GetTicketAction>
When you are sending the data you specify utf-16 as encoding.
But when you are reading the response you do not specify an encoding, so the default platform encoding is used.
So exchange this line:
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
with this (assuming the response also is encoded in utf-16):
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"utf-16"));
You should actually check the response header to learn which encoding has been used.
So after much searching I found the answer to this. The xml is read as gibberish because it is Gzip compressed. The way to read this is by using the
GZIPInputStream. This is because the XML is compressed differently.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip");
InputStreamReader in = new InputStreamReader (new GZIPInputStream(connection.getInputStream()));
String str;
while (true) {
int ch = in.read();
if (ch==-1) {
break;
}
Related
I am developing an application in Android Studio, where I will use the registered data of a web system based on PHP and Mysql. I was able to connect with the code below, I also managed to register directly through the application, but how would I do to bring the data in Android using PHP and Mysql?
Connection code
package br.com.perttutigestao.acessosistema;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Conexao {
public static String postDados(String urlUsuario, String parametrosUsuarios){
URL url;
HttpURLConnection connection = null;
try{
url = new URL(urlUsuario);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Lenght","" + Integer.toString(parametrosUsuarios.getBytes().length));
connection.setRequestProperty("Content-Language","pt-BR");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
outputStreamWriter.write(parametrosUsuarios);
outputStreamWriter.flush();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String linha;
StringBuffer resposta = new StringBuffer();
while ((linha = bufferedReader.readLine()) != null){
resposta.append(linha);
resposta.append('\r');
}
bufferedReader.close();
return resposta.toString();
}catch (Exception erro){
return null;
}finally {
if(connection != null){
connection.disconnect();
}
}
}
}
PHP
<?php
$conexao = mysqli_connect('localhost','root','success','projeto');
$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");
while($jm = mysqli_fetch_array($sql)){
$mostrar[] = $jm["Email"];
$mostrar[] = $jm["Senha"];
}
echo json_encode($mostrar);
I'm starting to develop in Android and I do not have much experience with Java.
You can try to use Asynctask for getting data from web
What i want?
I'm developing a Java application using the HttpUrlConnection library to send a POST and return the response from the site.
What is going on?
The code does not display syntax errors but when I execute it, it prints the message "propertyValue: false" even though I have not put any command to print anything.
What i need?
I need to know where this error is (propertyValue: false), because as I said, it does not show as if it had an error.
source:
import java.util.*;
import java.io.*;
import java.net.*;
public class Main
{
public static void main(String[] args) throws IOException
{
String target = "http://google.com";
String parameters = "contentOfPost";
URL url = new URL(target);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try{
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", parameters + Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "pt-BR");
conn.setRequestProperty("Referer", "https://www.google.com");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line=null;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (IOException e){}
}
}
Out: propertyValue:false
Trying to develop a speech to text application using Google's API with below code
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.testng.annotations.Test;
public class Speech2Text_Test {
#Test
public void f() {
try{
Path path = Paths.get("out.flac");
byte[] data = Files.readAllBytes(path);
String request = "https://www.google.com/"+
"speech-api/v2/recognize?"+
"xjerr=1&client=speech2text&lang=en-US&maxresults=10"+
"output=json&key=<My Key>";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
connection.setRequestProperty("User-Agent", "speech2text");
connection.setConnectTimeout(60000);
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.write(data);
wr.flush();
wr.close();
connection.disconnect();
System.out.println("Done");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
however after running the class (which sends .flac file to Google api) am getting as "{"result":[]}" Instead of the utterances of the audio file converted to text, what could be the cases Google returns the result as "{"result":[]}"?
Ran into the same issue my self. I found that is was the format of the flac file. It needs to be 16-bit PCM and mono otherwise you get the null result back. I use http://www.audacityteam.org/ to check/convert my files.
So in a nutshell, I'm just trying to get a small working skeleton program that I can use to sort of learn about Http communication and "feel" my way around to figure out what I will eventually need for a bigger program I am working on. This particular code here is actually just a chopped up version of an example from the Apache libraries. I could compile the examples listed on the Apache website, but they didn't run properly, giving a "java.net.ConnectException". I figured it had to do with Windows c-blocking a program like this from making a connection, and that I would need to run it as an administrator. I then tried taking the code and throwing it into an executable jar file, but I get a Cannot-find-or-load-main-class error. Am I an idiot or is the Apache library a little outdated/not fit for Win 8/something else?
Code below:
package NewProject;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
class NewProject
{
public static void main(String[] args) throws Exception
{
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost("localhost", 8080);
coreContext.setTargetHost(host);
Out os = new Out("TestOut.txt");
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
try
{
String[] targets =
{
"http://www.google.com/"
};
for (int i = 0; i < targets.length; i++)
{
if (!conn.isOpen())
{
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
os.println(">> Request URI: " + request.getRequestLine().getUri());
httpexecutor.preProcess(request, httpproc, coreContext);
HttpResponse response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
os.println("<< Response: " + response.getStatusLine());
os.println(EntityUtils.toString(response.getEntity()));
os.println("==============");
if (!connStrategy.keepAlive(response, coreContext))
{
conn.close();
}
else
{
os.println("Connection kept alive...");
}
}
}
catch (IndexOutOfBoundsException iob)
{
os.println("What happened here?");
}
finally
{
conn.close();
}
return;
}
}
... they didn't run properly, giving a "java.net.ConnectException"
That could be caused by lots of things. There are clues in the exception message ... which you chose not to share with us.
... "Cannot find or load Main-Class"
Again multiple possible causes, and there are clues in the exception message ... which you chose not to share with us.
But the fact that you have created a JAR file plus the "Main-Class" hint in the error message fragment you provided suggest that you made a mistake in the creation of the JAR file; i.e. you used the wrong name for the "Main-Class" attribute.
Given that source code, the "Main-Class" attribute should be "NewProject.NewProject". I suspect you set it to something else.
A second possibility is that you haven't handled the dependency on the Apache library correctly. The Apache classes need to be on the classpath specified by the JAR file. (You can't use a -cp argument or $CLASSPATH when you launch with java -jar.)
Am I an idiot or is the Apache library a little outdated/not fit for Win 8/something else?
There is nothing wrong with the Apache library.
The code you posted seems a little low level (e.g. interacting directly with Socket connections). The code posted below should give you what it sounds like you are looking for. The classes used also give you a lot of inroads into setting and getting http parameters (e.g. headers, time-outs, etc).
package org.yaorma.example.http.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
String response;
response = get("http://www.google.com");
System.out.println("RESPONSE FROM GET -----------------------------------------");
System.out.println(response);
response = post("http://httpbin.org/post", "This is the message I posted to httpbin.org/post");
System.out.println("RESPONSE FROM POST -----------------------------------------");
System.out.println(response);
}
/**
* Method to post a request to a given URL.
*/
public static String post(String urlString, String message) {
try {
// get a connection
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// set the parameters
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// send the message
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(message);
writer.flush();
writer.close();
os.close();
// get the response
conn.connect();
InputStream content = (InputStream) conn.getInputStream();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String rtn = "";
String line;
while ((line = in.readLine()) != null) {
rtn += line + "\n";
}
return rtn;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
/**
* Method to do a get from a given URL.
*/
public static String get(String urlString) {
try {
// get a connection
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// set the parameters
conn.setRequestMethod("GET");
conn.setDoOutput(true);
// get the response
conn.connect();
InputStream content = (InputStream) conn.getInputStream();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String rtn = "";
String line;
while ((line = in.readLine()) != null) {
rtn += line + "\n";
}
return rtn;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
How come I am only allowed to make posts to .com url's but not .asmx url's? Im a bit confused as what I want to generally do is send xml content to a .asmx url web service eventually. Can anyone supply me with tips why this doesn't work, and how I can post to a .asmx file?
public class POSTSenderExample {
public String echoCuties(String query) throws IOException {
// Encode the query
String encodedQuery = URLEncoder.encode(query, "UTF-8");
// This is the data that is going to be send to itcuties.com via POST request
// 'e' parameter contains data to echo
String postData = "e=" + encodedQuery;
URL url = new URL("http://echo.itgeeeks.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
// Write data
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
// Read response
StringBuilder responseSB = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
responseSB.append(line);
// Close streams
br.close();
os.close();
return responseSB.toString();
}
// Run this example
public static void main(String[] args) {
try {
System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Using "POST" is correct.
Instead of calling
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
you have to call
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
(if you are using utf-8 encoding which is probably the case).
You also have to set the SOAP Action in the http- Header:
connection.setRequestProperty("SOAPAction", SOAPAction);
You can find the SOAP Action eihter in the wsdl- file. What I did to find out all expected Parameters: I used a working WS Client, and traced the TCP traffic in order to find out the expected HTTP headers.