I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:
Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
", Name: " + json_data.getString("Name") +
", Years: " + json_data.getString("Age") +
", Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+", Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content", data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards
Use HttpURLConnection, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permission android:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
new ReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class ReceiveData extends AsyncTask<URL, Integer, Long> {
String response = "";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder feedback = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
public void getData() throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnection client = null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a
// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStream os = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
#Override
protected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloaded
final byte[] result = response.getBytes();
Long numOfBytes = Long.valueOf(result.length);
return numOfBytes;
}
protected void onPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.
InputCode input = new InputCode();
input.passToDisplay(myContext, response);
}
}
Use Volley as defined here. It's far more easier.
Hi can anyone Help in giving the connections for this Java code with Kafka Connections
Thanks in Advance
package example.producer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
public class TwitterStreamConsumer extends Thread {
private static final String STREAM_URI = "https://stream.twitter.com/1.1/statuses/filter.json";
public void run(){
try{
System.out.println("Starting Twitter public stream consumer thread.");
// Enter your consumer key and secret below
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey("xxxxx")
.apiSecret("xxxxx")
.build();
// Set your access token
Token accessToken = new Token("xxxxx", "xxxxxx");
// Let's generate the request
//System.out.println("Connecting to Twitter Public Stream");
OAuthRequest request = new OAuthRequest(Verb.POST, STREAM_URI);
request.addHeader("version", "HTTP/1.1");
request.addHeader("host", "stream.twitter.com");
request.setConnectionKeepAlive(true);
request.addHeader("user-agent", "Twitter Stream Reader");
request.addBodyParameter("track", "**screenname**"); // Set keywords you'd like to track here
service.signRequest(accessToken, request);
Response response = request.send();
// Create a reader to read Twitter's stream
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String[] args){
final TwitterStreamConsumer streamConsumer = new TwitterStreamConsumer(); // final because we will later pull the latest Tweet
streamConsumer.start();
}
}
Hi can any one Suggest me how to connect this Java code with Apache Kafka. I have tried in many ways but it is not getting right. can any one help in this ????
Thanks in Advance
getStream() method of Response class is declared as private, so it cannot be accessed to get the input stream.
private static final String topic = "twitter-feed-topic";
private static final String STREAM_URI = "https://api.twitter.com/1.1/statuses/home_timeline.json";
System.out.println("Starting Twitter public stream consumer thread");
Properties properties = new Properties();
properties.put("metadata.broker.list", "localhost:9092");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
ProducerConfig config = new ProducerConfig(properties);
Producer<String, String> producer = new Producer<String, String>(config);
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey("Api Key")
.apiSecret("Api Secret key")
.build();
Scanner in = new Scanner(System.in);
// Obtain the Request Token
Token requestToken = service.getRequestToken();
// authorize scribe here
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("enter the verifier number ");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
// access the token
Token accessToken = service.getAccessToken(requestToken, verifier);
OAuthRequest request = new OAuthRequest(Verb.GET, STREAM_URI, service);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
InputStream is = new ByteArrayInputStream((response.getBody()).getBytes(StandardCharsets.UTF_8));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line;
try {
while ((line = inputReader.readLine()) != null) {
KeyedMessage<String, String> message = new KeyedMessage<String, String>(topic, line);
producer.send(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
above twitter kafka producer example is running fine. I hope this helps!
package example.producer;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class TwitterStreamConsumer7 extends Thread {
private static final String STREAM_URI = "https://stream.twitter.com/1.1/statuses/filter.json";
public void run(){
try{
FileReader f = new FileReader("/home/trainings/Desktop/Streamin/input1.csv");
BufferedReader bf = new BufferedReader(f);
String Screen_Name="";
while((Screen_Name=bf.readLine())!=null)
{
System.out.println("Starting Twitter public stream consumer thread.");
System.out.println(Screen_Name);
// Enter your consumer key and secret below
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey("ZRra7TMrssssssssssssssssxxxxxxxxxxx")
.apiSecret("LgUhEY4R8xxxxxxxxxxxxxxxxxxQw069D")
.build();
// Set your access token
Token accessToken = new Token("349211dddddddddddddddhyv4AL01lMRVN", "gqNqPuWoSxxxxxxxxxxxxxxxxxxxxkz1xCrzxWMUgd3kZ");
Properties props = new Properties();
props.put("metadata.broker.list", "localhost:9092");
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("partitioner.class", "example.producer.SimplePartitioner");
props.put("request.required.acks", "1");
props.put("retry.backoff.ms", "150");
props.put("message.send.max.retries","10");
props.put("topic.metadata.refresh.interval.ms","0");
ProducerConfig config = new ProducerConfig(props);
final Producer<String, String> producer = new Producer<String, String>(config);
// Let's generate the request
//System.out.println("Connecting to Twitter Public Stream");
OAuthRequest request = new OAuthRequest(Verb.POST, STREAM_URI);
request.addHeader("version", "HTTP/1.1");
request.addHeader("host", "stream.twitter.com");
request.setConnectionKeepAlive(true);
request.addHeader("user-agent", "Twitter Stream Reader");
request.addBodyParameter("track", Screen_Name); // Set keywords you'd like to track here
service.signRequest(accessToken, request);
Response response = request.send();
// Create a reader to read Twitter's stream
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getStream()));
String line;
while ((line = reader.readLine()) != null) {
KeyedMessage<String, String> data = new KeyedMessage<String, String>("twitter_events5",line);
System.out.println(line);
producer.send(data);
Thread.sleep(1000);
}
//}
}
}
catch (IOException ioe){
ioe.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
TwitterStreamConsumer7 streamConsumer = new TwitterStreamConsumer7(); // final because we will later pull the latest Tweet
streamConsumer.start();
}
}
Solved the Issue it will be helpful
Kafka Producer using Spark Streaming..
package com.multipleproducer.sparkstreaming.Multiplekafkaproducersparkstreaming;
import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Twitterdata {
public static void Run(String ConsumerKey, String ConsumerSecret,
String AccessToken, String AccessTokenSecret ) {
Properties properties = new Properties();
properties.put("metadata.broker.list", "localhost:9092");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
properties.put("client.id","camus");
ProducerConfig producerConfig = new ProducerConfig(properties);
final Producer<String, String> producer = new Producer<String, String>(producerConfig);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey(ConsumerKey);
cb.setOAuthConsumerSecret(ConsumerSecret);
cb.setOAuthAccessToken(AccessToken);
cb.setOAuthAccessTokenSecret(AccessTokenSecret);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
//kafka.javaapi.producer.Producer<String, String> producer = new kafka.javaapi.producer.Producer<String, String>(producerConfig);
System.out.println("##################### TWITTER___ STARTED ###########################");
StatusListener listener = new StatusListener() {
public void onDeletionNotice(
StatusDeletionNotice statusDeletionNotice) {
// TODO Auto-generated method stub
}
public void onException(Exception ex) {
// TODO Auto-generated method stub
}
public void onScrubGeo(long userId, long upToStatusId) {
// TODO Auto-generated method stub
}
public void onStallWarning(StallWarning warning) {
// TODO Auto-generated method stub
}
public void onStatus(Status data) {
// TODO Auto-generated method stub
twitter4j.User user = data.getUser();
String userdata = user.toString();
userdata = userdata.replaceAll("UserJSONImpl", "");
System.out.println();
String topic="twitterdata";
KeyedMessage<String, String> info = new KeyedMessage<String,String>(topic,userdata);
producer.send(info);
System.out.println(info);
/*JSONObject obj=new JSONObject();
obj.put("UserId", user.getId());
obj.put("Name",user.getName());
obj.put("ScreenName",user.getScreenName());
obj.put("CreatedAt",user.getCreatedAt());
obj.put("Location",user.getLocation());
obj.put("TimeZone",user.getTimeZone() );
obj.put("Lang",user.getLang());
obj.put("UtcOffset",user.getUtcOffset());
obj.put("Description",user.getDescription());
obj.put("FavouritesCount", user.getFavouritesCount());
obj.put("FollowersCount",user.getFollowersCount());
obj.put("FriendsCount",user.getFriendsCount());
obj.put("ListedCount", user.getListedCount());
obj.put("URL",user.getURL());
obj.put("StatusesCount",user.getStatusesCount());
obj.put("OriginalProfileImageURL",user.getOriginalProfileImageURLHttps());
obj.put("Tweets",data.getText());
obj.put("CurrentUserRetweetId",data.getCurrentUserRetweetId());
obj.put("InReplyToUserId",data.getInReplyToUserId());
obj.put("InReplyToScreenName", data.getInReplyToScreenName());
obj.put("getSource", data.getSource());
System.out.println(obj);*/
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = { "BigTappIndia" };
fq.track(keywords);
// track Singapore location
//double[][] location = { { Latitude }, { Longitude } };
//fq.locations(location);
twitterStream.addListener(listener);
twitterStream.filter(fq);
twitterStream.sample();
}
public static void main(String args[]){
Twitterdata.Run("consumerkey",
"ConsumerSecret",
"AccessToken",
"AccessTokenSecret");
}
}
Kafka Producer using Twitter Hash_tag
package com.multipleproducer.sparkstreaming.Multiplekafkaproducersparkstreaming;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import com.google.common.collect.Lists;
import com.twitter.hbc.ClientBuilder;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Constants;
import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint;
import com.twitter.hbc.core.processor.StringDelimitedProcessor;
import com.twitter.hbc.httpclient.auth.Authentication;
import com.twitter.hbc.httpclient.auth.OAuth1;
/**
* Hello world!
*
*/
public class TwitterHash_tag
{
private static final String topic = "Hash_tag";
public static void run(String consumerKey, String consumerSecret,
String token, String secret) throws InterruptedException {
Properties properties = new Properties();
properties.put("metadata.broker.list", "localhost:9092");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
properties.put("client.id","camus");
ProducerConfig producerConfig = new ProducerConfig(properties);
Producer<String, String> producer = new Producer<String, String>(producerConfig);
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
// add some track terms in hashtag
endpoint.trackTerms(Lists.newArrayList("",
"#India"));
Authentication auth = new OAuth1(consumerKey, consumerSecret, token,
secret);
// Authentication auth = new BasicAuth(username, password);
// Create a new BasicClient. By default gzip is enabled.
Client client = new ClientBuilder().hosts(Constants.STREAM_HOST)
.endpoint(endpoint).authentication(auth)
.processor(new StringDelimitedProcessor(queue)).build();
// Establish a connection
client.connect();
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 10; msgRead++) {
KeyedMessage<String, String> message = null;
try {
message = new KeyedMessage<String, String>(topic, queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
producer.send(message);
System.out.println(message);
}
producer.close();
client.stop();
}
public static void main( String[] args ) throws InterruptedException
{
TwitterHash_tag.run("consumerKey", "consumerSecretkey",
" AccessToken", "AccessTokenSecret");
}
}
Good evening, I got this server and client here.
WebServer
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class WebServer {
public static void main(String[] args) throws Exception {
HttpServer http = HttpServer.create(new InetSocketAddress(8000), 0);
http.createContext("/test", new MyHandler());
http.setExecutor(null); // creates a default executor
http.start();
//NimServer nimserver = new NimServer(32778);
//nimserver.serve();
}
static class MyHandler implements HttpHandler {
//AtomicInteger atomicInteger = new AtomicInteger(0);
//int theValue = atomicInteger.get();
#Override
public void handle(final HttpExchange t) throws IOException {
final String response;
final String requestMethod = t.getRequestMethod();
if ("GET".equals(requestMethod)) {
// response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
}
else if ("POST".equals(requestMethod)) {
// atomicInteger.set(0);
int clientno = new DataInputStream(t.getRequestBody()).readInt();
System.out.println("Send from Client: " + clientno);
int newclientno = clientno + 1;
System.out.println("Increased by Server: " + newclientno);
new DataOutputStream(t.getResponseBody()).writeInt(newclientno);
}
else {
throw new IOException("Unsupported method");
}
//t.sendResponseHeaders(200, response.length());
//final OutputStream os = t.getResponseBody();
//os.write(newclientno);
//os.close();
}
}
}
HttpClient
import java.net.*;
import java.io.*;
public class HttpClient {
public static int clientno = 0;
public static void main(String[] args) throws Exception {
//NimMessage clientnumber = new NimMessage();
//clientnumber.nachricht = "Client No: " + clientno;
URL test = new URL("http://localhost:8000/test");
HttpURLConnection connect = (HttpURLConnection) test.openConnection();
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setRequestMethod("POST");
new DataOutputStream(connect.getOutputStream ()).writeInt(clientno);//send int out
int newclientno = new DataInputStream(connect.getInputStream()).readInt();
System.out.println("Send from Server: " + newclientno);
//BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
//String inputLine;
//System.out.println(clientnumber.createJsonNachricht().toString());
//while ((inputLine = in.readLine()) != null)
// System.out.println(inputLine);
//in.close();
}
}
I was able to send the integer clinetno from the client to the server and increase it at the server. But i can not figure out how to send the new integer newclientno back to the client and display it on the console. Any suggestions what i did wrong?
Okay i found my mistake, i had to add an header in the server to complete the connection. Which i already had but did not noticed it.
t.sendResponseHeaders(200, 0);
I am trying to serialize an object in a HttpHandler class.
I have 2 files, Server3.java:
package server3;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server3 {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Kjo eshte nje pergjigje nga serveri! n";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
Personat obj = new Personat();
ObjectOutputStream objOut = new ObjectOutputStream(t.getResponseBody());
objOut.writeObject(obj);
objOut.close();
}
}
}
class Personat implements Serializable{
private static final long serialVersionUID = 1L;
int ID=3;
String Name="Andi";
}
and Client3.java:
package server3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//te gjithe personat qe jan ne database me nej objekt
public class Client3 {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("http://localhost:3333");
HttpURLConnection s = (HttpURLConnection) url.openConnection();
s.setDoOutput(true);
s.setDoInput(true);
s.setRequestMethod("POST");
s.setUseCaches(false);
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
ObjectInputStream ios = new ObjectInputStream(s.getInputStream());
Personat oin = (Personat) ios.readObject();
String emri=oin.Name;
System.out.println(emri);
ios.close();
s.disconnect();
} catch (IOException ex) {
System.err.println(ex);
System.out.print(ex);
}
}
}
But when I run it eclipse shows me
java.io.EOFException Kjo eshte nje pergjigje nga serveri! njava.io.EOFException`
and I cant understand why.
The problem is that you are trying to fit both the string response and the object into response.length() bytes. What happens is that only response.length() bytes are sent and so if you try to read more you get the EOFException.
If you instead set the responseLength parameter to be 0 it will allow you to transmit an arbitrary amount of data
t.sendResponseHeaders(200, 0);
You also shouldn't close the stream if you are going to write more data into it. Don't call os.close() until all the writing is complete.
I need to send an email using SSL (SMTPS) and authentification. In apache Commons Net however there seems to be either AuthenticatingSMTPClient (no SSL, though it extends SMTPSClient?) or SMTPSClient (no authentication?), I need a combination of both (SSL + authentication). Anyone knows how I can do this? Thanks!
I know it is too late to reply to this but for future reference for others, AuthenticatingSMTPClient does provide ssl + authentication as it is extending SMTPSClient. Below is the sample code, one has to do modifications where I have commented with numerals (e.g. //1).
Code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.io.Util;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient.AUTH_METHOD;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
public final class SMTPMail
{
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException
{
String sender, recipient, subject, filename, server;
List<String> ccList = new ArrayList<String>();
FileReader fileReader = null;
Writer writer;
SimpleSMTPHeader header;
AuthenticatingSMTPClient client;
server = "<smtp server>"; // 1
try
{
sender = "<your user name>"; // 2
recipient = "<recipient>"; // 3
subject = "<mail subject>"; // 4
header = new SimpleSMTPHeader(sender, recipient, subject);
filename = "hello.txt"; //This will be the body of your mail //5
try
{
fileReader = new FileReader(filename);
}
catch (FileNotFoundException e)
{
System.err.println("File not found. " + e.getMessage());
}
client = new AuthenticatingSMTPClient("TLS", false);
client.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out), true));
client.connect(server);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode()))
{
client.disconnect();
System.err.println("SMTP server refused connection.");
System.exit(1);
}
client.login("hostname.testing.smtp.api"); //6
if(client.execTLS())
{
if(client.auth(AUTH_METHOD.LOGIN, "<your user name>", "<your password>")) //7
{
client.setSender(sender);
client.addRecipient(recipient);
for (String recpt : ccList) {
client.addRecipient(recpt);
}
writer = client.sendMessageData();
if (writer != null)
{
writer.write(header.toString());
Util.copyReader(fileReader, writer);
writer.close();
client.completePendingCommand();
}
if (fileReader != null ) {
fileReader.close();
}
}
}
client.logout();
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}